406根据身高重建队列

406根据身高重建队列

题目描述

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。

注意:

总人数少于1100人。

示例

输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

思路

这个题是要求我们按照输入的每个人的身高及他前面有几个人来重新整理队列。

我们可以先将高个子排好,向高个子的前面插入比他矮的,那么他的k值就不会受影响。

而同样高的时候,k值较大的应该放在后面

例如 [7,1],[7,0] 的情况是不可能出现的

public static int[][] reconstructQueue(int[][] people) {
        if (people == null || people.length <= 1) {
            return people;
        }
        Arrays.sort(people, (p1, p2) -> p1[0] == p2[0] ? p1[1] - p2[1] : p2[0] - p1[0]);
        List<int[]> ans = new ArrayList<>();
        for (int[] person : people) {
            ans.add(person[1], person);
        }

        return ans.toArray(new int[ans.size()][]);
    }

顺便说一下List的add方法

void add(int index, E element);

index为可选参数,表示要插入的元素在list中的索引位置,如果索引超出list.size就会抛出IndexOutOfBoundsException 索引越界异常。

如果index所在索引本就有元素,那么将原顺序中索引以后的位置全部向后移动一位,之后再向index插入元素

ArrayList:

        List<Integer> arrayList = new ArrayList<>();
        arrayList.add(0,1);
        System.out.println(arrayList);
        arrayList.add(0,2);
        System.out.println(arrayList);
        arrayList.add(0,3);
        System.out.println(arrayList);
        arrayList.add(0,4);
        System.out.println(arrayList);
        arrayList.add(2,5);
        System.out.println(arrayList);
        arrayList.add(4,6);
        System.out.println(arrayList);

结果为

[1]
[2, 1]
[3, 2, 1]
[4, 3, 2, 1]
[4, 3, 5, 2, 1]
[4, 3, 5, 2, 6, 1]

LinkedList:

        List<Integer> linkedList = new LinkedList<>();
        linkedList.add(0,1);
        System.out.println(linkedList);
        linkedList.add(0,2);
        System.out.println(linkedList);
        linkedList.add(0,3);
        System.out.println(linkedList);
        linkedList.add(0,4);
        System.out.println(linkedList);
        linkedList.add(2,5);
        System.out.println(linkedList);
        linkedList.add(4,6);
        System.out.println(linkedList);

结果为

[1]
[2, 1]
[3, 2, 1]
[4, 3, 2, 1]
[4, 3, 5, 2, 1]
[4, 3, 5, 2, 6, 1]

在本题中,因为第一个人的k值必为0,所以可以直接使用add方法来添加

posted @ 2020-11-16 10:44  嘲_风  阅读(90)  评论(0)    收藏  举报