Queue Reconstruction by Height
A.题意
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.
题目给出了一串乱序的的pair,要求你把它排好序,pair的第一个数是身高,第二个是该元素前面有几个元素比它高或者和它一样高,排序完的队伍应该使队伍序列符合这些数字的意义
这是leetcode上的例子
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]]
B.思路
按这道题我们应该把大的数据先排完然后逐步插入小的数字,这样就能简单地实现,我们先按身高从小到大的顺序把数据排序,身高相同的第二个数字小的在前面,然后先把高身高插入目标序列,这低身高的在后面插入就不会影响到后面的元素插入
C.代码实现
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
std::sort(people.begin(), people.end(), comp);
std::vector< pair<int, int> > answer;
for (auto i : people)
{
answer.insert(i.second + answer.begin(),i);
}
return answer;
}
static bool comp(const pair<int, int>& a, const pair<int, int>& b)
{
return a.first == b.first ? a.second < b.second : a.first > b.first;
}
};