1 题目
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]]
2 尝试解
2.1 分析
对于一列身高不同的人[5,7,2,6,4,7],分别记录其前面不矮于他的人的个数,即[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]。现在把这个数组打乱,即给定一个数组[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]],还原回人群的排队顺序。
首先个子唯一最矮的人是不会影响其他人的计数的,比如[4,4]去掉后,其他人的计数不发生变化。但是据此可以确定[4,4]的位置就是[4],因为其他人都比他高,他前面刚好有4个人,所以result[4] = [4,4]。这时候剩下的位置是[0,1,2,3,5,6]。
再考虑剩下的个子最矮的人,即[5,0]和[5,2]。在个子最矮的人不唯一时,去掉最后的人,不影响其他人的计数。即去掉[5,2](和[4,4])后,其他人的计数不发生变化。但可以确定[5,2]在剩余的空位中排第3,因为其他的人都不矮于他,所以他前面有且只能有2个人,所以result[2]=[5,2]。同理result[0]=[5,0]。
即将人群按照高度由小到大排序,高度相同的,计数大的即排名靠后的视为更小的。然后根据他们的计数找到在剩余位置中的相对位置。
2.2 代码
class Solution {
public:
static bool cmp(const vector<int>&a, const vector<int>&b){
return (a[0] < b[0]) || (a[0]==b[0]&&a[1] > b[1]);
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> result(people.size());
sort(people.begin(),people.end(),cmp);
vector<int> pos;
for(int i = 0; i < people.size(); i++) pos.push_back(i);
for(auto person : people){
result[pos[person[1]]] = person;
pos.erase(pos.begin()+person[1]);
}
return result;
}
};
3 标准解
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
auto comp = [](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(), comp);
vector<pair<int, int>> res;
for (auto& p : people)
res.insert(res.begin() + p.second, p);
return res;
}