LeetCode OJ 406. Queue Reconstruction by Height

20 篇文章 0 订阅
1 篇文章 0 订阅

LeetCode OJ 406. Queue Reconstruction by Height


Description

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的降序排列,h相等时,按照k的升序排列。然后我们再一个个把元素插入到结果队列中。插入的方法是:插入到当前队列下标为k的位置。因为我们之前插入的都是比这个元素的h值大的元素,因此当前元素的h值就是队列中所剩下未插入结果队列的h值最大的元素了。而且k值是升序排列的,保证了结果插入的过程中不会越界。
eg.
题目中所给的输入进行排序后
Input: [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
结果Result首先插入第一个元素[7,0]:
Result: [[7,0]]
插入第二个元素[7,1],在Result中下标为1的位置,即偏移量为1:
Result: [[7,0], [7,1]]
插入第三个元素[6,1]:
Result: [[7,0], [6,1], [7,1]]
插入第四个元素[5,0]:
Result: [[5,0], [7,0], [6,1], [7,1]]
插入第五个元素[5,2]:
Result: [[5,0], [7,0], [5,2], [6,1], [7,1]]
插入第六个元素[4,4]:
Result: [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Note:

std::sort函数是全局的,如果第三个参数cmp不是静态成员函数或者全局函数,运行都会报错。非静态函数是依赖于具体对象的,因此调用sort函数时,只能调用不依赖于对象的静态函数cmp。

代码

个人github代码链接

class Solution {
public:
    static bool cmp(pair<int, int> p1, pair<int, int> p2){
        return (p1.first > p2.first) || ((p1.first == p2.first) && (p1.second < p2.second));
    }
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> ans;
        sort(people.begin(), people.end(), cmp);
        for(auto p:people){
            ans.insert(ans.begin() + p.second, p);
        }
        return ans;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值