leetcode:(406)Queue Reconstruction by Height(java)

论坛 期权论坛 脚本     
已经匿名di用户   2022-7-2 21:51   2009   0

题目:

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

题目描述:

一直一串数组,对数组进行排序。每个数组是(h,k)的形式,h代表数组值的大小,k代表前面有几个大于或者等于该数组值的个数。

解题思路:

首先将数组按照h降序 ,k升序进行排序。即:先比较h值的大小(按照h降序排序),如果h值相同,比较k值(按照k值升序进行排序),然后从头向尾遍历数组串,将每个数组放在队列k的位置。具体代码及思路如下:

package Leetcode_Github;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class GreedyThought_ReconstructQueue_406_1108 {
    public int[][] reconstructQueue(int[][] people){
        if (people == null || people.length == 0 || people[0].length == 0) {
            return new int[0][0];
        }

        //按照身高降序,K值升序进行排序
        Arrays.sort(people, (m, n) -> (m[0] == n[0] ? m[1] - n[1] : n[0] - m[0]));

        //将people中的每个数组放到队列peo[1]处
        List<int[]> queue = new ArrayList<>();
        for (int[] peo : people) {
            queue.add(peo[1], peo);
        }

        //将队列转换成数组,返回
        return queue.toArray(new int[queue.size()][]);
    }
}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP