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/
解題方法:
矮個子對于高個子在這道題中并沒有什么意義,所以我們先處理最高的,然后矮個子可以根據(jù)第二個值往其中插入,從而不會影響高個子。對于相同高的人,我們優(yōu)先處理第二個值小的,因為相同高度的人可以互相影響。
- 所以先把數(shù)組按照身高將序,當(dāng)身高相同第二個值升序排列。
- 再遍歷一遍數(shù)組, 把每個人插到與其第二個值相對應(yīng)的位置即可。
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;
}