LeetCode-Queue Reconstruction by Height

来源:互联网 发布:java中多态的理解 编辑:程序博客网 时间:2024/05/18 03:11

1. Queue Reconstruction by Height (Medium)

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

Analysis
首先将people按照第一个数字的降序,第二个数字的升序排序。例如题目给定的
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
排序之后是
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
然后依次将排序后的pair按照第二个数字作为index插入result中。这样每一步插入都是满足题意要求的,最后返回结果。

代码:

class Solution {public:    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        vector<pair<int, int>> result;        sort(people.begin(), people.end(), [](pair<int, int> a, pair<int, int> b){            return a.first > b.first || (a.first == b.first && a.second < b.second);        });        for (auto p: people) {            result.insert(result.begin() + p.second, p);        }        return result;    }};
原创粉丝点击