[leetcode 406]Queue Reconstruction by Height

来源:互联网 发布:如何用qq注册淘宝账号 编辑:程序博客网 时间:2024/05/21 09:12

问题描述

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

代码

算法简介:按照k由小到大的顺序插入,时间复杂度O(n^2)

#include <algorithm>bool compare(pair<int,int>a,pair<int,int>b) {    if (a.second < b.second)        return true;    else if (a.second == b.second && a.first < b.first)        return true;    return false;}class Solution {public:    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        sort(people.begin(),people.end(),compare);        list<pair<int,int> > tmp;        list<pair<int,int> >::iterator liter;        int cnt = 0;        for (vector<pair<int,int> >::iterator iter = people.begin();iter != people.end();++iter) {            cnt = 0;            liter = tmp.begin();            while (liter != tmp.end() && !(cnt == iter->second && liter->first >= iter->first)) {                if (liter->first >= iter->first)                    ++cnt;                ++liter;            }            tmp.insert(liter,*iter);        }        vector<pair<int,int> > result;        for (liter = tmp.begin();liter != tmp.end();++liter)            result.push_back(*liter);        return result;    }};
0 0
原创粉丝点击