Leetcode C++《热题 Hot 100-48》406.根据身高重建队列

Leetcode C++《热题 Hot 100-48》406.根据身高重建队列

  1. 题目

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

  1. 思路
  • 思路很巧妙的题目。将输入按照从h从大到小,k从小到大排序。逐个将h插入到答案中,按照k的值,刚好满足新插入的需求。
  • 时间复杂度为排序复杂度,平均nlogn,最坏n平方
  1. 代码
class Solution {
public:
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
        vector<pair<int, int>> temp;
        vector<pair<int, int>> res;
        vector<vector<int>> outputRes;
        for (int i = 0; i < people.size(); i++) {
            temp.push_back(make_pair(people[i][0], people[i][1]));
        }
        sort(temp.begin(), temp.end(), cmp);
        for (int i = 0; i < temp.size(); i++) {
            //cout << temp[i].first << " " << temp[i].second << endl;
            res.insert(res.begin()+temp[i].second, temp[i]);
        }
        for (int i = 0; i < res.size(); i++) {
            vector<int> oneres;
            oneres.push_back(res[i].first);
            oneres.push_back(res[i].second);
            outputRes.push_back(oneres);
        }
        return outputRes;

    }

    static bool cmp(pair<int, int> a, pair<int, int> b) {
        if (a.first > b.first)
            return true;
        else if (a.first == b.first && a.second < b.second)
            return true;
        else
            return false;
    }
};
发布了205 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104446741
今日推荐