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

题解:

身高降序排列,人数升序排列.然后按照人数插入对应的位置

参考代码:

 1 class Solution 
 2 {
 3 public:
 4     vector<vector<int>> reconstructQueue(vector<vector<int>>& people) 
 5     {
 6         //身高降序排列,人数升序排列
 7         sort(people.begin(), people.end(), [](const vector<int>& a, const vector<int>& b)
 8         {
 9             if(a[0] > b[0]) return true;
10             if(a[0] == b[0] && a[1] <b[1]) return true;
11             return false;
12         });
13 
14         vector<vector<int>> res;
15         for(int i = 0; i < people.size(); i++)
16             res.insert(res.begin() + people[i][1], people[i]);
17             
18         return res;
19     }
20 };
C++

 

posted @ 2020-02-18 00:01  StarHai  阅读(300)  评论(0编辑  收藏  举报