LeetCode #406 - Queue Reconstruction by Height

本文介绍了一种基于特定条件下的队列重建算法。该算法通过排序及特定规则的插入操作来实现,确保了每个人前面恰好有k个比他高或者跟其同样高的人站在其前面。文章详细解释了算法步骤,并提供了具体的示例输入输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

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

一组数组表示一队人,h表示高度,k表示他之前的最大可以挡住他(高度大于或等于h)的人数,求这个数组的排列方法,满足所有的人。

首先需要对数组排序,然后直接将元素(h,k)插入结果数组的第k位上,同时要保证后面插入的元素不会影响之前的元素,所以应该是h越高的元素先插入,因为h较小的元素插入不会挡住之前h较高的元素,同时当h相等时,应该是k越小的元素先插入,因为后面插入的k更大,即插入在之前的元素后面,保证不会挡住之前的元素。排序的方法直接重定义sort函数即可。

class Solution {
public:
    static bool comp(pair<int,int> a,pair<int,int> b)
    {
        if(a.first!=b.first) return a.first<b.first;
        else if(a.first==b.first) return a.second>b.second;
    }
    
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int,int>> result;
        sort(people.begin(),people.end(),comp);
        for(int i=people.size()-1;i>=0;i--)
        {
            result.insert(result.begin()+people[i].second,people[i]);
        }
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值