LeetCode 406 Queue Reconstruction by Height (排序 思维)

来源:互联网 发布:欧洲的经济数据 编辑:程序博客网 时间:2024/05/21 13: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 toh. 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]]


题目链接:https://leetcode.com/problems/queue-reconstruction-by-height/

题目分析:先按h从大到小排序,值相同的话按k从小到大排序,相同数字间的顺序就看k的大小来排序,所以这样处理完以后,直接把当前pair插到对应的地方即可,原来c++的vetcor还有insert这个函数。。。用在本题极其方便

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


0 0