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.
这里写图片描述

思路分析

这道题大意是根据每个people的h和站在他前面的h不小于他的people数量k,确定出所有people前后位置的队列。先是按照h递减排序people,如果h相同就按照k递增排序people,排序直接调用STL的sort函数;声明一个空容器queue用来存储最终的结果,从容器people的第一个元素开始,依次将每个people插入queue中,其中,每个people插入queue的位置距离queue头部的偏移量等于k。
根据上述思路,分析Example的过程如下:

  • 排序结果:[7,0], [7,1], [6, 1], [5,0], [5,2], [4,4]
  • 往queue插入people:[7,0]->[7,0], [7,1]->[7,0], [6,1], [7,1]
    ->[5,0], [7,0], [6,1], [7,1]->[5,0], [7,0], [5,2], [6,1], [7,1]
    ->[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]

代码实现

class Solution {
public:
    static bool compare(const pair<int, int>& a, const pair<int, int>& b) {
        if ((a.first > b.first) || ((a.first == b.first) && (a.second < b.second)))
            return true;
        else return false;
    }
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        vector<pair<int, int>> queue;
        //排序:h降序排序,k升序排序
        sort(people.begin(), people.end(), compare);
        for (vector<pair<int, int>>::iterator iter = people.begin(); iter != people.end(); iter++) {
            queue.insert(queue.begin()+(*iter).second, (*iter));
        }
        return queue;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值