[LeetCode] 406. Queue Reconstruction by Height

Problem:

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”的人数,以给出的例子简单说明:

观察结果可见,排序后的队列的第一个元素为[5,0],表示该位置高度为5,排在其前并且高度不小于5的人数为0,第三个元素为

[5,2],2表示排在其前并且高度不小于5的人数为2( [5,0], [7,0]均满足条件)...以此类推...


解题思路:首先按照高度将原数组的元素排序,高的排在前(高度相等时,按照k值的规律要求排,即k值小的在前),上述例子

经过排序后的结果为[ [7,0], [7,1], [6, 1], [5, 0], [5, 2], [4, 4]],在此基础上再次进行调整,调整的方法为:

新建一个数组result,将排序后的原数组的元素依次插入,插入方法为result.insert(result.begin() + p.second, p),这样一来,既

保证了k值的排序符合要求,也保证了当k值相同时,高度较小的元素能排在前。


Solution:

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        if (people.size() == 0) {
            people.clear();
            return people;
        }
        sortQueue(people);
        vector<pair<int, int>> result;
        for (auto p : people) 
            result.insert(result.begin() + p.second, p);
        return result;
    }
    
    void sortQueue(vector<pair<int, int>>& people) {
        pair<int,int> temp;
        for (int i = 0; i < people.size()-1; i++) {
            for (int j = 0; i + j < people.size()-1; j++) {
                if (people[j].first < people[j+1].first || (people[j].first == people[j+1].first &&
                                                           people[j].second > people[j+1].second)) {
                    temp = people[j];
                    people[j] = people[j+1];
                    people[j+1] = temp;
                }
            }
        }
    }
};


这里我采用了冒泡排序对初始数组进行排序,显然当数组规模增大时,效率会受到影响,Discuss中有个大神给出了

一个更高效的解法,参考https://discuss.leetcode.com/topic/60470/6-lines-concise-c

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值