【LeetCode-排序】根据身高重建队列

题目描述

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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]]

题目链接: https://leetcode-cn.com/problems/queue-reconstruction-by-height/

思路

将整数对 (h, k) 按照 h 降序排序,如果 h 相同,则按照 k 升序排序。排序完毕后,令结果数组为 ans,从头开始遍历数组,将数组中的每个元素插入到 ans[k] 的位置。代码如下:

class Solution {
public:
    static bool cmp(const vector<int>& a, const vector<int>& b){
        if(a[0]!=b[0]) return a[0]>b[0]; // 按照 h 降序排序
        else return a[1]<b[1]; // 按照 k 升序排序
    }

    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        sort(people.begin(), people.end(), cmp);
        vector<vector<int>> ans;
        for(auto v:people){
            ans.insert(ans.begin()+v[1], v);
        }
        return ans;
    }
};
  • 时间复杂度:O(n^2)
  • 空间复杂度:O(n)
posted @ 2020-05-24 21:09  Flix  阅读(711)  评论(0编辑  收藏  举报