题解:Queue Reconstruction by Height

来源:互联网 发布:创世纪 知乎 编辑:程序博客网 时间:2024/05/16 05:57

题目如下:

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较小者排前),随后依次根据k的值(因为前面有的人数算是比较决定性的条件)选择插入的位置把排序后的向量每一个元素放进新的向量,最后返回该向量。

代码如下:

class Solution {public:static bool cmp(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> > result;        sort(people.begin(), people.end(), cmp);        for (int i = 0; i < people.size(); i++) {            result.insert(result.begin() + people[i].second, people[i]);        }        return result;    }};