LeetCode 406. 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.
题意大致为:有一队伍,每个人用一个键值对来表示,键值对的第一个数表示这个人的身高,第二个数表示排在这个人前面的人且身高高于这个人的人数量;题目给定这些键值对,要求返回一个队列,使得该队列中人的排列顺序满足上述性质。

二、解题思路

一开始的思路是:先将人按身高从低到高排,如果身高相同则按第二个数从低到高排,然后每次从第一位开始遍历该数组,一旦找到符合要求的就加入到结果队列中并将其从原数组中删除,这样做是对结果队列的每一位逐一找到正确的人,缺点在于每向结果队列中加进一个人,都需要知道目前队列中的人比他高的有多少,才能决定这个人是不是合适加进去,实现起来比较麻烦。
比较机智而且简洁的算法是:从身高高到低遍历每一个人,当每个人要加进队列的时候,由于比他先进入队列的人都比他高,所以他的键值对的第二个值是多少,他就插入到队列中的第几个,且由于后插入的数都比他小,就算插入位置在他之前,也不会影响到他

三、C++代码

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) {
        sort(people.begin(), people.end(), cmp);
        vector<pair<int, int>> result;
        for(auto j : people)
        result.insert(result.begin() + j.second, j) ;
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值