LeetCode 406. Queue Reconstruction by Height

先根据身高排序,高的在前。然后对people进行遍历(从高到矮放入队伍),对于当前的人来说,比他高的人都已经排好队了,因此只要根据k插入队伍即可。

代码非常简洁。

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), [](const pair<int,int> &a, const pair<int,int> &b){
            if (a.first==b.first) return a.second<b.second;
            return a.first>b.first;
        });
        vector<pair<int,int>> res;
        for (auto x:people)
            res.insert(res.begin()+x.second, x);
        return res;
    }
};

 

posted @ 2018-11-10 03:33  約束の空  阅读(120)  评论(0)    收藏  举报