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]]
分析
这一题只需要理清一个思路就可以:一定按照身高从高到低放置。因此高的人的站位决定着低的人站位。
以题目的例子为例,我们首先放置高度为7的,按照k从小到大的次序放置
[7,0] [7,1]
然后放置身高为6的,这个时候6的位置一定是确定的
[7,0] [6,1] [7,1]
再放置身高为5的,先放[5,0],再放[5,2],放置的位置就是第k个位置
[5,0] [7,0] [5,2] [6,1] [7,1]
一次类推,即可得到所有的排列。
Code
class Solution {
public:
static bool cmp(pair<int, int>& a, pair<int, int>& b)
{
return a.first < b.first || (a.first == b.first && a.second > b.second);
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> res;
sort(people.begin(), people.end(), cmp);
for (int i = people.size()-1; i >= 0; i--)
{
res.insert(res.begin() + people[i].second,
people[i]);
}
return res;
}
};
运行效率
Runtime: 40 ms, faster than 95.92% of C++ online submissions for Queue Reconstruction by Height.
Memory Usage: 10.3 MB, less than 85.56% of C++ online submissions for Queue Reconstruction by Height.