LeetCode 406. Queue Reconstruction by Height(根据身高重建队列)

题目描述:一个学生用两个分量 (h, k) 描述,h 表示身高,k 表示排在前面的有 k 个学生的身高比他高或者和他一样高。

   public int[][] reconstructQueue(int[][] people) {
        if(people.length == 0 || people[0].length == 0) {
            return new int[0][0];
        }
        //按照height h降序排列,若h相同时再按照k升序排列
        Arrays.sort(people, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                return a[0] == b[0] ? a[1] - b[1] : b[0] - a[0];
            }
        });

        List<int[]> queue = new ArrayList<>();
        //K值定义为 排在h前面且身高大于或等于h的人数 
        //因为从身高降序开始插入,此时所有人身高都大于等于h
        //因此K值即为需要插入的位置
        for(int[] p : people) {
            queue.add(p[1], p);
        }

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

在这里插入图片描述

发布了581 篇原创文章 · 获赞 97 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/gx17864373822/article/details/104899378