leetcode 406. Queue Reconstruction by Height

来源:互联网 发布:C# js escape 编辑:程序博客网 时间:2024/05/22 06:14

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.

若N个人排队,每个人用一个pair(h,k)表示,h–人的身高,k–此人前面有k个人的身高>=k
这N的pair的顺序打乱了,要求重新构造原始的排队队列

Note:
The number of people is less than 1,100. 队列长度<1100

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.分析

如何还原队列,即求出每个人的位置。pair

3.代码

class Solution {public:    static bool mycmp(pair<int, int> a, pair<int, int> b) {        if (a.first != b.first)            return a.first > b.first;        else            return a.second < b.second;    }    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        vector<pair<int, int>> res;        std::sort(people.begin(), people.end(), mycmp);//原始队列排序        for (auto p:people)            res.insert(res.begin() + p.second, p);//插入到结果队列        return res;    }};
原创粉丝点击