[LeetCode] 406. Queue Reconstruction by Height(按身高重排队列)

Posted Zhongju.copy()

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 406. Queue Reconstruction by Height(按身高重排队列)相关的知识,希望对你有一定的参考价值。

Description

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integer (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.
假设你有一队人随机地站在队伍里。每一个人以一对整数 (h, k) 表示,其中 h 是这个人的身高,k 是在这个人前面身高大于等于 h 的人数。设计一个算法重新构建队列。

Note

The number of people is less than 1,100.
队伍人数小于 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]]

Hints

  1. What can you say about the position of the shortest person?
    If the position of the shortest person is i, how many people would be in front of the shortest person?
    关于队伍里最矮的人,你获取到什么有用信息?
    如果队伍里最矮的人在第 i 位,这个人前面会有多少人?

  2. Once you fix the position of the shortest person, what can you say about the position of the second shortest person?
    一旦固定了最矮的人的位置,那么第二矮的人呢?

Solution

这题最后想要得到的结果是每一个人的 k 值都符合题意。本题的一种做法来自于 discussion,先把队列按从高到矮,k 值由低到高的顺序排列,然后依次按照 k 值安插进最后的结果中,代码如下:

class Solution {
    fun reconstructQueue(people: Array<IntArray>): Array<IntArray> {
        people.sortWith(Comparator { p1, p2 ->
            if (p1[0] == p2[0]) {
                p1[1] - p2[1]
            } else {
                p2[0] - p1[0]
            }
        })
        val result = arrayListOf<IntArray>()
        for (p in people) {
            result.add(p[1], p)
        }
        return result.toTypedArray()
    }
}






以上是关于[LeetCode] 406. Queue Reconstruction by Height(按身高重排队列)的主要内容,如果未能解决你的问题,请参考以下文章

[leetcode] 406.Queue Reconstruction by Height

[LeetCode] 406. Queue Reconstruction by Height(按身高重排队列)

LeetCode 406.Queue Reconstruction by Height

LeetCode 406. Queue Reconstruction by Height

LeetCode 406. Queue Reconstruction by Height

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