Leetcode:406. 根据身高重建队列

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。

注意:
总人数少于1100人。

示例

输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

解题思路:

特殊排序。先对人群进行排序,排序方式如下:

static bool cmp(pair<int, int> a, pair<int, int>b) {
        if (a.first == b.first) return a.second < b.second;
        return a.first > b.first;
    }

  1. 接着,获取第一个元素到新的数组res中。
  2. 遍历之后的元素poeple[pos]逐个插入res中。
  3. 要明白,排序之后后面的元素升高都小于或等于res中的所有人,poeple[pos].k的值,可以确定poeple[pos]应该位于res数组的第k+1个,因此在对应位置插入即可。
  4. 仔细思考,上面这个排序,它巧妙地避免了res中找不到k+1位置地尴尬,简直玄学。

C++代码
class Solution {
public:
    static bool cmp(pair<int, int> a, pair<int, int>b) {
        if (a.first == b.first) return a.second < b.second;
        return a.first > b.first;
    }
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), Solution::cmp);
        int size = people.size(),i;
        if (size <= 1) return people;
        vector<pair<int, int>>  res;
        res.push_back(people[0]);
        for (i = 2; i <= size; i++) {
            res.insert(res.begin()+people[i - 1].second, people[i - 1]);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_23523409/article/details/84836216