Problem:
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],h代表高度,k
代表排在当前位置前面并且满足 “高度 >= h”的人数,以给出的例子简单说明:
观察结果可见,排序后的队列的第一个元素为[5,0],表示该位置高度为5,排在其前并且高度不小于5的人数为0,第三个元素为
[5,2],2表示排在其前并且高度不小于5的人数为2( [5,0], [7,0]均满足条件)...以此类推...
解题思路:首先按照高度将原数组的元素排序,高的排在前(高度相等时,按照k值的规律要求排,即k值小的在前),上述例子
经过排序后的结果为[ [7,0], [7,1], [6, 1], [5, 0], [5, 2], [4, 4]],在此基础上再次进行调整,调整的方法为:
新建一个数组result,将排序后的原数组的元素依次插入,插入方法为result.insert(result.begin() + p.second, p),这样一来,既
保证了k值的排序符合要求,也保证了当k值相同时,高度较小的元素能排在前。
Solution:
class Solution {
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
if (people.size() == 0) {
people.clear();
return people;
}
sortQueue(people);
vector<pair<int, int>> result;
for (auto p : people)
result.insert(result.begin() + p.second, p);
return result;
}
void sortQueue(vector<pair<int, int>>& people) {
pair<int,int> temp;
for (int i = 0; i < people.size()-1; i++) {
for (int j = 0; i + j < people.size()-1; j++) {
if (people[j].first < people[j+1].first || (people[j].first == people[j+1].first &&
people[j].second > people[j+1].second)) {
temp = people[j];
people[j] = people[j+1];
people[j+1] = temp;
}
}
}
}
};
这里我采用了冒泡排序对初始数组进行排序,显然当数组规模增大时,效率会受到影响,Discuss中有个大神给出了
一个更高效的解法,参考:https://discuss.leetcode.com/topic/60470/6-lines-concise-c