天天看点

Leetcode406. 根据身高重新构造队列Leetcode406. Queue Reconstruction by Height

Leetcode406. 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.

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]]

解题分析

一拿到这道题,可能刚开始会是毫无头绪的,不知从何下手。但粗略想一下,可能会觉得应该将他们按身高排序。

但问题的关键在于要如何根据他们的身高来确定位置,从而实现要求的队列。一种想法是,将他们按身高从小到大排序,然后按照比他们高的人数对应插入位置,如果位置不为空,就遍历数组找到不为空的位置然后插入。之后再遍历数组的每个元素,如果他所在位置在他前面比他高的人数不等于他实际的位置,那么就往后遍历数组,找到第一个比他高的进行位置的交换。这样做不是不可以,但是可能显得有些过于麻烦了。

那有什么更好的做法呢?这里我们用到了vector的insert函数,它表示在对应位置插入元素,如果该位置有元素,就自动将已插入的元素往后移。说实话,这个函数并不怎么用,以至于我都忘记了。结合题目的要求,我们可以往vector里面对应位置插入身高比较高的元素,然后后面如果有位置重叠,就自动将身高比较高的元素往后挪,这样问题就顺利解决了,比上面一种做法也简单了许多。

源代码

class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        int i, size = people.size();
        vector<pair<int, int>> v;
        sort(people.begin(), people.end(), [](const pair<int, int>& x, const pair<int, int>& y) -> int {
            return (x.first > y.first) || (x.first == y.first && x.second < y.second);
        });
        for (i = ; i < size; i++) {
            v.insert(v.begin() + people[i].second, people[i]);
        }
        return v;
    }
};
           

以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~