Leetcode 406. Queue Reconstruction by Height

来源:互联网 发布:大四迷茫 知乎 编辑:程序博客网 时间:2024/06/05 12:53

Leetcode 406. Queue Reconstruction by Height

source url

题目描述

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.

输入:
输出:排序后的队伍
如:

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

思路1.

先对输入的序列对进行排序,首先根据高度排序,高度大的在前面;其次,当高度相同时,k小的在前。上述排序过后结果为:[[7,0],[7,1],[6,1],[5,0],[5,2],[4,4]]。随后,组成序列。基本思路是,大的数字先插入,插入位置为k。这样,能保证在插入第(i,k)时,已有序列本身都>=i,这是插到第k个位置是合理的。这种贪心策略每一步都是合理的。

代码

class Solution {public:    static bool comp(pair<int, int>& p1, pair<int, int>& p2){                            return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);     }    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {        vector<pair<int, int>> res;        sort(people.begin(), people.end(), this->comp);        for (int i =0;i<people.size();i++) {            pair<int, int>& p = people[i];            res.insert(res.begin() + p.second, p);}        return res;    }};
0 0
原创粉丝点击