Week Training: 406 Queue Reconstruction by Height

来源:互联网 发布:网络摄像机排行榜 编辑:程序博客网 时间:2024/05/22 06:57

Before, I traverse the vector times and times to find the one to insert into the new vector each time, with a low efficiency. However, I was impressed by another ingenious method and used it without hesitation. We first sort the vector descending first element, then the ascending second element. After that, we just insert each element in the sorted vector based on its second value. An amazing way to solve this problem.

class Solution {public:    static bool comp(pair<int, int> a, pair<int, int> b){        return a.first > b.first || (a.first == b.first && a.second < b.second);    }    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        vector<pair<int, int>> re;        int size = people.size();        sort(people.begin(),people.end(),comp);        for(int i=0;i<people.size();i++){            re.insert(re.begin()+people[i].second,people[i]);        }        return re;    }};


0 0