假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
解题思路:
贪心加冒泡
首先把people根据身高从高到低,人数从小到大进行排序
然后把每个people和他前面的people进行比较,如果前面的people的身高高于他,那么就交换两位people
同时,要确保每个people前面的人数是正确的
class Solution {
public:
static bool cmp(vector<int>& a,vector<int>& b){
if(a[0] != b[0]) return a[0] > b[0];
else return a[1] < b[1];
}
vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
vector<vector<int>> res = people;
sort(res.begin(),res.end(),cmp);
for(int index = 1;index < res.size();index++){
int j = index;
while(j){
if(res[j-1][0] > res[j][0] &&
res[j][1] < j //这里控制位置){
swap(res[j],res[j-1]);
j--;
}else{
break;
}
}
}
return res;
}
};