LN : leetcode 406 Queue Reconstruction by Height

lc 406 Queue Reconstruction by Height


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]]

贪心算法 Accepted

首先,利用sort函数对people数组进行排序,使其中的顺序变为高度最高的在最前面,当高度一样时,令k值小的排在前面,优先满足最高且k最小的人的需求。

最后,依次将人插入到当前ans第k+1个的位置,得到的ans数组即为所求排序。

正确性解释:最高且k较小的人具有更高的优先性,因为当其已被插入,之后再插入的人,对在他之前比他高或相等的人的个数没有影响。

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        auto cmp = [](pair<int, int>& p1, pair<int, int>& p2) {
            return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);
        };
        sort(people.begin(), people.end(), cmp);
        vector<pair<int, int>> ans;
        for (auto&p : people)   ans.insert(ans.begin()+p.second, p);
        return ans;
    }
};
原文地址:https://www.cnblogs.com/renleimlj/p/7667528.html