题目描述
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.
思路分析
这道题大意是根据每个people的h和站在他前面的h不小于他的people数量k,确定出所有people前后位置的队列。先是按照h递减排序people,如果h相同就按照k递增排序people,排序直接调用STL的sort函数;声明一个空容器queue用来存储最终的结果,从容器people的第一个元素开始,依次将每个people插入queue中,其中,每个people插入queue的位置距离queue头部的偏移量等于k。
根据上述思路,分析Example的过程如下:
- 排序结果:[7,0], [7,1], [6, 1], [5,0], [5,2], [4,4]
- 往queue插入people:[7,0]->[7,0], [7,1]->[7,0], [6,1], [7,1]
->[5,0], [7,0], [6,1], [7,1]->[5,0], [7,0], [5,2], [6,1], [7,1]
->[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]
代码实现
class Solution {
public:
static bool compare(const pair<int, int>& a, const pair<int, int>& b) {
if ((a.first > b.first) || ((a.first == b.first) && (a.second < b.second)))
return true;
else return false;
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> queue;
//排序:h降序排序,k升序排序
sort(people.begin(), people.end(), compare);
for (vector<pair<int, int>>::iterator iter = people.begin(); iter != people.end(); iter++) {
queue.insert(queue.begin()+(*iter).second, (*iter));
}
return queue;
}
};