Queue Reconstruction by Height 题解

Queue Reconstruction by Height 题解


题目描述:

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.


链接:406. Queue Reconstruction by Height


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

算法描述:

根据题意,我们将对 vector 中的 pair 进行规则排序,pair 中第一个数表示身高,第二个数表示在其之前有多少个人身高不低于他(我们用“排名”表示),第一步,我们先按照这样的思路进行一个初始排序:按照身高从高到低的顺序依次排列,如果两个人身高一样,比较他们的“排名”,“排名”小的在前。这样,我们就能得到初始序列:[ [7,0],[7,1],[6,1],[5,0],[5,2],[4,4] ]。

第二步,我们用这样的策略:创建结果 vector 为 new_queue, 并对初始初始序列的每个 pair 进行遍历,按照“排名”的值(表示每个 pair 的相对位置)在结果 new_queue 中进行插入。如:遍历到 [7,0] 时,“排序”为 0,将其插入到 0 的位置,此时 vector 为[[7,0]];之后遍历到 [7,1] 时,“排序”为 1 ,将其插入到 1 的位置,此时 vector 为[ [7,0],[7,1] ];当其遍历到[6,1]时,“排序”为 1,将其插入到 1 的位置,此时 vector 为[ [7,0],[6,1],[7,1] ];按照这样的方法即可完成。算法复杂度为O(n²) 。


代码:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int,int>> new_queue;
        auto method=[](pair<int,int> &p1, pair<int,int> &p2){
            return p1.first>p2.first || p1.first==p2.first && p1.second<p2.second;
        };
        
        sort(people.begin(),people.end(),method);
        for(auto &it : people){
            new_queue.insert(new_queue.begin()+it.second,it);
        }
        return new_queue;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值