题目描述
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]]
解题思路
首先对输入进行排序,因为是双关键词,所以不能直接用sort函数,需要重写sort。按pair的首位(first)为主码进行升序排序,如果first相同,再按second降序排列。
排序之后使用stl的insert函数进行插入,insert的用法为(position, value),如果要写成三个数字的话,第二位是重复插入的个数,(position,count,value)。
我们可以根据排序后的数组,来找到贪心的策略。
排序后的数组为:
[7,0] [7,1] [6,1] [5,0] [5,2] [4,4]
来从[7,0]开始输出每次多加一个后的排列结果,可以清楚的发现规律:
[7,0]
[7,0],[7,1]
[7,0],[6,1],[7,1]
[5,0],[7,0],[6,1],[7,1]
[5,0],[7,0],[5,2],[6,1],[7,1]
[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]
可以发现,每次插入的位置都恰好是最新的初始位置+待插入的second值。
复杂度分析
时间复杂度为O(N)。
代码如下(完整的,包括main的测试):
#include <iostream>
#include <vector>
using namespace std;
class Solution {
private:
static bool comp (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;
//return a.first>b.first || (a.first == b.first && a.second < b.second);
}
public:
vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
vector<pair<int, int>>result;
vector<int>::iterator it;
sort(people.begin(), people.end(), comp);
int n=people.size();
for (int i=0; i<n ; i++){
result.insert(result.begin()+people[i].second,people[i]);
//cout << i << " :" << result[i].first << result[i].second << endl;
}
return people;
}
};
int main(int argc, const char * argv[]) {
vector<pair<int, int>>me;
me.push_back(pair<int, int>(7,0));
me.push_back(pair<int, int>(7,1));
me.push_back(pair<int, int>(5,0));
me.push_back(pair<int, int>(4,4));
me.push_back(pair<int, int>(5,2));
me.push_back(pair<int, int>(6,1));
vector<pair<int, int>>out;
Solution my;
out=my.reconstructQueue(me);
for (int i=0; i<me.size(); i++) {
cout << out[i].first <<"," << out[i].second << endl;
}
return 0;
}