406. Queue Reconstruction by Height

问题描述:

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

解题思路:

这道题十分有趣,给我们一个数组,里面装的pair,p.first代表的是这个人的身高, p.second代表的是在他前面比这个人高或身高与之相同的的人的个数,要求我们重新构造这个队,让这个队满足对里面的的人的要求。

我们可以想到重写比较器。

关键是怎样比的?

由于p.second代表的是前面身高≥这个人的个数,所以我们首先对身高从大到小排序,然后对人数从小到大排序。

然后对新数组根据人数确定位置并且插入。

代码:

class Solution {
public:
    struct cmp{
        bool operator() (const pair<int, int> &p1, const pair<int, int> p2){
            return p1.first > p2.first ||(p1.first == p2.first && p1.second < p2.second);
        }  
    };
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), cmp());
        vector<pair<int, int>> ret;
        for(auto p: people){
            ret.insert(ret.begin() + p.second, p);
        }
        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9222469.html