leetcode406. Queue Reconstruction by Height

时间:2022-06-19
本文章向大家介绍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]]

假设有一组人站成一堆,每个人都记录下了自己的高度,以及在自己前面有多少个不比自己矮的人。现在请按照这个信息将这组人放在队列中正确的位置上并返回。

思路和代码

刚开始我试图用分治法来解决,因为每一个小队列中,高度最矮且站在自己前面的高个最少的人一定位于k位置上。但是这样解决其实复杂化了问题。

可以从另一个角度来想,首先我们知道,同等高度的人,其相对位置一定是根据k的值从小到大排列的。即k越大,则该同等高度的人一定在另一个同等高度的人后面。如果我们从高到低将人们插入队列中,可以知道,k的值就该人在当前队列中的下标,如:

[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
首先将其按照h和k排序,得出结果:
[[7,0],[7,1],[6,1],[5,1],[5,0],[5,2],[4,4]]

当前结果队列为[]
将[7,0]插入下标为0的位置上 结果队列[[7,0]]
将[7,1]插入下标为1的位置上 结果队列[[7,0],[7,1]]
将[6,1]插入下标为1的位置上 结果队列[[7,0],[6,1],[7,1]]
按照这种规则,依次按照顺序和k的值将数据插入结果队列中

代码如下:

    public int[][] reconstructQueue(int[][] people) {
        int[][] result = new int[people.length][2];
        Arrays.sort(people, new Comparator<int[]>() {

            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0];
            }
            
        });
        for(int i = 0 ; i<people.length ; i++) {
            int pos = people[i][1];
            for (int j = i; j > pos; j--) {
                result[j] = result[j - 1];
            }    
            result[pos] = people[i];
        }
        return result;
    }