Queue Reconstruction by Height

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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是人的高度,k是这个人的高度大于或等于h的人数。 编写算法来重建队列。

2,题目思路

对于这道题,要求的是对一系列人的身高进行一次重新排列。

其中,每一组数据是用一个pair来进行表示的。第一个参数表示的是这个人的身高,第二个参数表示的则是队列中前面有几个人比他高。

因此,我们可以按照身高的高低,首先插入身高最高、前面没有比他高的人,然后,依次按照身高插入,插入的位置直接按照第二个参数所表示的前面还有几个人,插入到对应的位置里(有几个人,索引位置就是几)。

E.g.
input: [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
subarray after step 1: [[7,0], [7,1]]
subarray after step 2: [[7,0], [6,1], [7,1]]

于是,我们应该首先对这个序列进行排序,按照身高从高到低的顺序进行排序,如果身高相同,那就按照前面还是否有人的顺序,来进行排列。

为此,我们可以对内置的sort重新定义一下排序规则,以实现对特殊数据结构排序的目的。

对于cmp的定义:
定义的sort中的cmp函数,在函数体部分,return的是一个表示优先级的语句。比如如果return的是 p1 < p2,则说明因为p1较小,因此p1优先级较高,于是整个数组的排列是按照从小到大的顺序排列了。

其中,cmp必须设置为全局函数或者静态函数

代码实现

static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        sort(people.begin(), people.end(), cmp);
        
        vector<pair<int, int>> res;
        for(auto &p : people)
            res.insert(res.begin() + p.second, p);
        
        return res;
    }
private:
    static bool cmp(pair<int, int>&p1, pair<int, int>&p2){
        return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值