Thursday, September 28, 2017

406. Queue Reconstruction by Height

https://leetcode.com/problems/queue-reconstruction-by-height/description/
Solution 1. Sort and insert
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> res;
        sort(people.begin(), people.end(),
             [&](pair<int, int> a, pair<int, int> b){
                 if(a.first!=b.first)return a.first>b.first;
                 else return a.second<b.second;
             });
        for(int i=0; i<people.size(); i++) {
            res.insert(res.begin()+people[i].second, people[i]);
        }
        return res;
    }
The sort could be:
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);

No comments:

Post a Comment