美文网首页
406. Queue Reconstruction by Hei

406. Queue Reconstruction by Hei

作者: 殷水臣 | 来源:发表于2017-02-20 22:20 被阅读0次

这道题也比较基础,算是贪心吧?每一步把当前最大最后的归位就好。

自己的解

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        int now = people.size();
        while (now != 0){
            int biggest = 0;
            for (int i = 0; i < now; i++){
                if (people[i].first > people[biggest].first){
                    biggest = i;
                }else if (people[i].first == people[biggest].first && people[i].second < people[biggest].second){
                    biggest = i;
                }
            }
            --now;
            swap(people[biggest], people[now]);
            pair <int, int> temp = people[now];
            for(int i = now; i <now + temp.second; i ++){
                people[i] = people[i+1];
            }
            people[now + temp.second] = temp; 
        }
    return people;
    }
};

别人家的解。。。

vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
    auto comp = [](const pair<int, int>& p1, const pair<int, int>& p2)
                    { return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); };
    sort(people.begin(), people.end(), comp);
    vector<pair<int, int>> res;
    for (auto& p : people) 
        res.insert(res.begin() + p.second, p);
    return res;
}

总结,多熟悉库函数T T

相关文章

网友评论

      本文标题:406. Queue Reconstruction by Hei

      本文链接:https://www.haomeiwen.com/subject/foxywttx.html