406. Queue Reconstruction by Height

来源:互联网 发布:淘宝货到付款怎么退款 编辑:程序博客网 时间:2024/06/06 18:35

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个人的身高大于等于他的身高h。

注意到,每次选身高最高的几个放入队列,因为他们比队列中的人都矮,所以不会破坏队列的性质,每个人放入序列的序号就等于k。

E.g.
input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
step 1: [[7,0], [7,1]]
step 2: [[7,0], [6,1], [7,1]]
step 3: [[[5,0], [7,0], [5,2], [6,1], [7,1]]
step 4: [[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

所以,我们先按高到矮排序,身高相同则按k从小到大排序,之后一个个按k插入队列。

class Solution {public:    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        //排序        sort(people.begin(), people.end(), [](const pair<int, int>& a, const pair<int, int>& b){            return a.first > b.first || (a.first == b.first && a.second < b.second);        });        vector<pair<int, int>> ans;        for(int i = 0; i < people.size(); i++){            ans.insert(ans.begin()+people[i].second, people[i]);        }        return ans;    }};
原创粉丝点击