Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers
(h, k)
, whereh
is the height of the person andk
is the number of people in front of this person who have a height greater than or equal toh
. Write an algorithm to reconstruct the queue.
Note:
The number of people is less than 1,100.
假設有隨機的人群在列隊中。每個人有一對整數
(h, k)
去描述他,h
是這個人的身高,k
是他前面有多少人比他高。寫一個演算法重新排序這個列隊。
提示:
描述人的數字小於 1,100。
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
的規則。
bool myCompare(vector<int> a, vector<int> b)
{
return (a[0] > b[0] || (a[0] == b[0] && a[1] < b[1]));
}
class Solution {
public:
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> ans;
sort(people.begin(), people.end(), myCompare);
for(int i = 0; i < people.size(); i++)
ans.insert(ans.begin() + people[i][1], people[i]);
return ans;
}
};
LeetCode
C++