问题描述:
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.
问题解决:
找的网上的算法
即首先对数组中的元素进行排序,对h从高到低排,若h相等,对k从低到高排
新建一个数组result
遍历排序后的原数组,一个一个数对取出来插入result,插入的偏移量为数对的k
代码如下:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>> result;
vector<pair<int, int>>::iterator iter1 = people.begin();
//排序
sort(people.begin(), people.end(), sortPair);
/*for(; iter1 != people.end(); iter1++) {
vector<pair<int, int>>::iterator iter2 = result.begin();
int i = (*iter1).second;
if(i > result.size()) result.push_back(*iter1);
else {
while(i--) iter2++;
result.insert(iter2, *iter1);
}
}*/
//遍历排序后的数组并插入result
for(auto p : people) {
result.insert(result.begin()+p.second,p);
}
return result;
}
//排序函数
static bool sortPair(const pair<int, int> &a, const pair<int, int> &b) {
if(a.first > b.first) return true;
if(a.first == b.first && a.second < b.second) return true;
return false;
}
};