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从小到大排序。
[7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
取出开头的元素,插入下面的队列中k个元素的后面。
[5,0] [7,0] [5,2] [6,1] [4,4] [7,1]
bool compare(pair<int, int> &a, pair<int, int> &b) {
if (a.first > b.first)
return true;
else if (a.first == b.first && a.second< b.second)
return true;
else return false;
}
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
sort(people.begin(), people.end(), compare);
vector<pair<int, int>> result;
for(auto i: people) {
result.insert(result.begin() + i.second, i);
}
return result;
}
};
哦,那个sort函数必须得定义全局,为啥。不管了,碎觉碎觉!
哇哇哇哇哇!!第一次自己纯手打leetcode题(编译过了后)一遍过,而且代码挺短(好吧用了标准库的sort),激动!!(虽然解法思路是看别人的哈哈哈)