Description:
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]]
Link:
https://leetcode.com/problems/queue-reconstruction-by-height/description/
解题方法:
矮个子对于高个子在这道题中并没有什么意义,所以我们先处理最高的,然后矮个子可以根据第二个值往其中插入,从而不会影响高个子。对于相同高的人,我们优先处理第二个值小的,因为相同高度的人可以互相影响。
- 所以先把数组按照身高将序,当身高相同第二个值升序排列。
- 再遍历一遍数组, 把每个人插到与其第二个值相对应的位置即可。
Time Complexity:
O(nlogn)
完整代码:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people)
{
sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b) {
if(a.first > b.first)
return true;
if(a.first == b.first)
return a.second < b.second;
return false;
});
vector<pair<int, int>> result;
for(auto a: people)
result.insert(result.begin() + a.second, a);
return result;
}