题目描述:
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]]
一组数组表示一队人,h表示高度,k表示他之前的最大可以挡住他(高度大于或等于h)的人数,求这个数组的排列方法,满足所有的人。
首先需要对数组排序,然后直接将元素(h,k)插入结果数组的第k位上,同时要保证后面插入的元素不会影响之前的元素,所以应该是h越高的元素先插入,因为h较小的元素插入不会挡住之前h较高的元素,同时当h相等时,应该是k越小的元素先插入,因为后面插入的k更大,即插入在之前的元素后面,保证不会挡住之前的元素。排序的方法直接重定义sort函数即可。
class Solution {
public:
static bool comp(pair<int,int> a,pair<int,int> b)
{
if(a.first!=b.first) return a.first<b.first;
else if(a.first==b.first) return a.second>b.second;
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int,int>> result;
sort(people.begin(),people.end(),comp);
for(int i=people.size()-1;i>=0;i--)
{
result.insert(result.begin()+people[i].second,people[i]);
}
return result;
}
};