题目描述:
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]]
题目大意:有一个队列,每个队列中的人都有一个标识:1.身高 2.前面有多少个人比TA高。重排队列使新队列满足标识。
思路:先对输入队列进行排序,按如下规则1.身高越高排越前 2.身高相同,“比TA高的人“越少排越前。然后将排序后的元素插入到一个新数组中,位置为数组起始位置+比TA高的人的数量。
这个方法其实是网上的解题方法,我想了一下:越高的人排越前,使得后插入的元素必定小于等于先插入的元素,从头按条件2的顺序安排位置保证了元素的位置在本次插入一定使队列正确,即使后插入的元素插入到已经插入的元素的前面也不会影响队列的正确性。
c++代码:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> ans;
sort(people.begin(), people.end(), cmp);
for (int i = 0; i < people.size(); i++)
{
ans.insert(ans.begin() + people[i].second, people[i]);
}
return ans;
}
static bool cmp(const pair<int, int>& a, const pair<int, int>& b)
{
return a.first > b.first || (a.first == b.first && a.second < b.second);
}
};