LeetCode 406. Queue Reconstruction by Height (Medium)

题目描述:

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]]
题目大意:有一个队列,每个队列中的人都有一个标识:1.身高 2.前面有多少个人比TA高。重排队列使新队列满足标识。

思路:先对输入队列进行排序,按如下规则1.身高越高排越前 2.身高相同,“比TA高的人“越少排越前。然后将排序后的元素插入到一个新数组中,位置为数组起始位置+比TA高的人的数量。
这个方法其实是网上的解题方法,我想了一下:越高的人排越前,使得后插入的元素必定小于等于先插入的元素,从头按条件2的顺序安排位置保证了元素的位置在本次插入一定使队列正确,即使后插入的元素插入到已经插入的元素的前面也不会影响队列的正确性。

c++代码:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> ans;
        sort(people.begin(), people.end(), cmp);
        for (int i = 0; i < people.size(); i++)
        {
            ans.insert(ans.begin() + people[i].second, people[i]);
        }
        return ans;
    }
    static bool cmp(const pair<int, int>& a, const pair<int, int>& b)
    {
        return a.first > b.first || (a.first == b.first && a.second < b.second);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值