406. Queue Reconstruction by Height(greedy)

来源:互联网 发布:淘宝手机版下载安卓版 编辑:程序博客网 时间:2024/06/16 22:45

1. 问题描述

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]]


2. 问题分析


问题简要的是在说,K值表示身高为h的人前面排有K个身高大于等于h的人。很明显可以确定下来的是,身高最高H的人,前面没有身高比H大的人,以此为突破口,可以继续迭代,身高为第二最高H2的人,前面除了身高为H的人,没有比H2更高的了。所以,采用贪心算法的策略,每次选出“最高”的插入队伍中,根据k值就可以知道当前的人应该插入到哪里,才能保证K值成立。


3. 算法设计

#include<iostream>#include<vector>#include<algorithm>using namespace std;/** 按身高从大到小排序,如果身高相同则按k值排序 */bool compare(pair<int, int>p1, pair<int, int> p2) {    return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);}/** 按身高从大到小插入,如果身高相同则k值小的在前* 以k值为索引插入每项,因为是按身高从大到小插入,从而保证了* K值为前面的h值大于当前h值的个数 */vector<pair<int, int> > reconstructQueue(vector<pair<int, int> >& people) {      sort(people.begin(), people.end(), compare);       vector<pair<int, int> > result;      for(int i = 0; i < people.size(); i++) {        result.insert(result.begin() + people[i].second, people[i]);      }      return result;}int main() {    pair<int, int> p1(7,0), p2(4,4), p3(7,1), p4(5,0), p5(6,1), p6(5,2);    vector<pair<int, int> > ans;    ans.insert(ans.end(), p1);    ans.insert(ans.end(), p2);    ans.insert(ans.end(), p3);    ans.insert(ans.end(), p4);    ans.insert(ans.end(), p5);    ans.insert(ans.end(), p6);    vector<pair<int, int> > res = reconstructQueue(ans);    for(int i = 0; i < res.size(); i++)        cout << "[ " << res[i].first << "," << res[i].second << " ]" << " "; } 

4. 算法优化


这一算法的时间复杂度为O(nlogn)

原创粉丝点击