leetcode - [406] Queue Reconstruction by Height

2020/06/23

问题描述

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.

给你一个嵌套数组,其中的元素也是一个数组,并且仅包含两个元素,

首元素代表这个人的高度h,尾元素代表在这个人之前比他高或等于的人的个数。

请重新排列这个数组。

举个例子:

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

解法1

梳理下思路:

首先,我们需要对首元素进行倒序排列,若首元素相等,则对尾元素进行升序排列。

排序完的结果:

[[7,0], [7,1], [6,1], [5,0], [5,2]], [4,4]

然后,根据尾元素依次往List<int[]>容器中插入。

来看下实现:

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        
        List<int[]> ans = new LinkedList<>();
        int len = people.length;
        if (len == 0) return new int[0][0];
        // Sort
        Arrays.sort(people, (a, b) -> a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]);
        
        for (int[] p: people){
            ans.add(p[1], p);
        }
        return ans.toArray(new int[ans.size()][]);
    }
}

Enjoy it !


一位喜欢提问、尝试的程序员

(转载本站文章请注明作者和出处 姚屹晨-yaoyichen

Post Directory