Leetcode406. 根据身高重新构造队列

本文介绍了LeetCode第406题——根据身高重建队列的问题,分析了如何利用身高和前面高的人数来重构队列。通过排序和vector的insert函数,可以简化解决问题的过程,实现队列的正确重建。并提供了相关解题代码。

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

Leetcode406. 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.

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

解题分析

一拿到这道题,可能刚开始会是毫无头绪的,不知从何下手。但粗略想一下,可能会觉得应该将他们按身高排序。
但问题的关键在于要如何根据他们的身高来确定位置,从而实现要求的队列。一种想法是,将他们按身高从小到大排序,然后按照比他们高的人数对应插入位置,如果位置不为空,就遍历数组找到不为空的位置然后插入。之后再遍历数组的每个元素,如果他所在位置在他前面比他高的人数不等于他实际的位置,那么就往后遍历数组,找到第一个比他高的进行位置的交换。这样做不是不可以,但是可能显得有些过于麻烦了。
那有什么更好的做法呢?这里我们用到了vector的insert函数,它表示在对应位置插入元素,如果该位置有元素,就自动将已插入的元素往后移。说实话,这个函数并不怎么用,以至于我都忘记了。结合题目的要求,我们可以往vector里面对应位置插入身高比较高的元素,然后后面如果有位置重叠,就自动将身高比较高的元素往后挪,这样问题就顺利解决了,比上面一种做法也简单了许多。

源代码

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        int i, size = people.size();
        vector<pair<int, int>> v;
        sort(people.begin(), people.end(), [](const pair<int, int>& x, const pair<int, int>& y) -> int {
            return (x.first > y.first) || (x.first == y.first && x.second < y.second);
        });
        for (i = 0; i < size; i++) {
            v.insert(v.begin() + people[i].second, people[i]);
        }
        return v;
    }
};

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值