LC 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]]
Runtime: 32 ms, faster than 52.69% of C++ online submissions for Queue Reconstruction by Height.
按身高降序排列,身高相同的按第二个数升序排列。
然后我们一个一个按照第二个数的index插入一个新的序列。这样做的好处是,插入后面的数不会对之前的数产生
影响。
但这种做法需要新开一个数组,如果你不想新开一个数组,可以在当前数组种修改,但如果是vector其实提升效果一般吧,最好开一个链表。
#include <assert.h>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
#define ALL(x) (x).begin(), (x).end()
using namespace std;
class Solution {
public:
static bool sortcmp(const pair<int,int> a, const pair<int,int> b){
if(a.first == b.first) return a.second < b.second;
return a.first > b.first;
}
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int,int>> ret;
if(people.empty()) return ret;
sort(ALL(people), sortcmp);
for(int i=0; i<people.size(); i++){
ret.insert(ret.begin() + people[i].second, people[i]);
}
return ret;
}
};