美文网首页
Leetcode 精选之贪心思想(根据身高重建队列)

Leetcode 精选之贪心思想(根据身高重建队列)

作者: Kevin_小飞象 | 来源:发表于2020-03-27 14:05 被阅读0次

题目描述

假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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+1 个位置。

身高 h 降序、个数 k 值升序,然后将某个学生插入队列的第 k 个位置中。

import java.util.*;
public class Main {
    
    public static void main(String[] args) {
        int[][] intervals = {
            {7,0},
            {4,4},
            {7,1},
            {5,0},
            {6,1},
            {5,2}
        };
        
        printArray(reconstructQueue(intervals));
       
    }

    public static int[][] reconstructQueue(int[][] people) {
        if (people == null || people.length == 0 || people[0].length == 0) {
            return new int[0][0];
        }
        Arrays.sort(people, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0]));
        List<int[]> queue = new ArrayList<>();
        for (int[] p : people) {
            queue.add(p[1], p);
        }
        return queue.toArray(new int[queue.size()][]);
    }
    
    public static void printArray(int[][] array) {
        for (int[] i : array) {
            for (int j : i) {
                System.out.print(j + " ");
            }
            System.out.print(",");
        }
    }
}

测试结果

image.png

相关文章

网友评论

      本文标题:Leetcode 精选之贪心思想(根据身高重建队列)

      本文链接:https://www.haomeiwen.com/subject/bbyluhtx.html