406. Queue Reconstruction by Height
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]]
解题思路
我先将vector中所有元素排序,h小的在前,h相同,k较大的在前(因为题目中k表示的是排在自己之前的大于等于的元素的个数,我在这里认为,k较大的是“小于”k较小的)。如题目给出的例子,排序后的结果如下:
[[4,4],[5,2],[5,0],[6,1],[7,1],[7,0]]
设置了一个标记位,标记这个元素是否放入结果中。
从排好序的第一个元素开始遍历,选择合适的位置。对于每个people[i],因为之前的元素都已经放入,而且之前的元素都比它小,所以将其放入结果时,只需考虑流出k的空位置放比它大的元素。即选择第k个为空的位置。
代码如下:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
if(people.size() == 0) {
return people;
}
for(int i = 0; i < people.size() - 1; i++) {
for(int j = i + 1; j < people.size(); j++) {
if(people[i].first > people[j].first || (people[i].first == people[j].first && people[i].second < people[j].second)) {
pair<int, int> temp = people[i];
people[i] = people[j];
people[j] = temp;
}
}
}
vector<int> tag(people.size());
vector<pair<int, int>> res(people.size());
for(int i = 0; i < people.size(); i++) {
int j = 0, k = 0;
for(j = 0, k = 0; j < people.size(); j++) {
if(k != people[i].second && tag[j] != 0) {
continue;
}
if(k != people[i].second && tag[j] == 0) {
k++;
continue;
}
if(k == people[i].second && tag[j] == 0) {
res[j] = people[i];
tag[j] = 1;
break;
}
}
}
return res;
}
};