• LeetCode 406. Queue Reconstruction by Height


    406. Queue Reconstruction by Height

    Description Submission Solutions Add to List

    • Total Accepted: 16876
    • Total Submissions: 30903
    • Difficulty: Medium
    • Contributors: Admin

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

    Subscribe to see which companies asked this question.

    【题目分析】

    题目给出了一些人的身高和这个人前面身高大于等于他的人数,对这些人进行排队,使得所有人的情况都得到满足。

    【思路】

    1. Pick out tallest group of people and sort them in a subarray (S). Since there's no other groups of people taller than them, therefore each guy's index will be just as same as his k value.
    2. For 2nd tallest group (and the rest), insert each one of them into (S) by k value. So on and so forth.

    首先找到身高最高的人并对他们进行排序。

    然后找到身高次高的人,按照他们的前面的人数把他们插入到最高的人群中。

    因此这是一个排序和插入的过程,按照身高进行降序排序,然后把身高相同的人按照k进行升序排序。每次取出身高相同的一组人,按照k值把他们插入到队列中。

    【java代码】

     1 public class Solution {
     2     public int[][] reconstructQueue(int[][] people) {
     3         Arrays.sort(people, new Comparator<int[]>(){
     4             public int compare(int[] a, int[] b) {
     5                 if(a[0] != b[0]) return -a[0]+b[0];
     6                 else return a[1]-b[1];
     7             }
     8         });
     9         
    10         List<int[]> res = new LinkedList<>();
    11         for(int[] p : people) {
    12             res.add(p[1], p);
    13         }
    14         
    15         return res.toArray(new int[people.length][]);
    16     }
    17 }
  • 相关阅读:
    数据分析的数据来源都有哪些?
    数据分析的技能要求及分析流程
    (原创)使用matlab-cftools拟合工具的问题
    Spring加载xml配置文件的方式
    Spring-ResolvableType可解决的数据类型
    从list中取N个随机生成一个集合
    AOP统一处理修改人、创建人、修改时间、创建时间
    Java依据集合元素的属性,集合相减
    java去掉数字后面的0
    数字格式化NumberFormat
  • 原文地址:https://www.cnblogs.com/liujinhong/p/6403353.html
Copyright © 2020-2023  润新知