题目
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]]
思路
这道题目我自己的思路是每次从数组中提取出
k
=
0
k=0
k=0且height最小的人push_back到result中,这个人的height为h,然后剩下的每个height小于h的人的k值减一,依次循环直到结束。但显然这并不是最优解,写出来只超过了10%不到的提交结果。
看了答案以后感觉这道题的思路还是挺新奇的,值得好好学习一下。最佳答案的思路不是像我这样按照位置找合适的人,而是把人一个个插入到当前队伍合适的位置上去。这种做法首先将队伍由高到矮排序,然后从最高的开始一个个插入到队伍当中去。假设当前轮到person p,对应的k值为k1,则只需要将p插到当前队伍的第k1+1个位置就可以保证前面有k1个人比p高,而之后更矮的人插入队伍不会改变这一点。依次插入完的结果就是最终的输出。
代码
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> result;
// use lambda expression as the third parameter
sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b){
return a.first > b.first || (a.first == b.first && a.second < b.second);
});
for (auto p: people) {
result.insert(result.begin() + p.second, p);
}
return result;
}
};