问题描述
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]]
思路分析
有一个list的pair,(h, k),h表示这个人的身高,k表示这个人之前有几个人的身高大于或等于他。要求重构这个list,使之符合这些pair的表现。
首先将最高的那些人排列好,因为高度都一样,所以按照k来排序即可。然后开始往里面加人,身高矮一个档的朋友们,因为一定比现在队列中的人矮,所以按照它们的k值的位置,插入到现在的list中就可以了,以此类推。
这个时候sort的优越性就体现出来了,按照规则,设计comparator,按照身高排序,如果身高相同,则前面人少的排前面。然后遍历排序后的list,插入到他们应该插入的位置即可。
代码
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
auto cmp = [](const pair<int, int>& p1, const 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>> res;
for (auto p : people){
res.insert(res.begin() + p.second, p);
}
return res;
}
};
时间复杂度:
未知
空间复杂度:
未知
反思
关键在于找对入手的方向,先从高的人开始,会容易思考这个问题。