1. 程式人生 > 實用技巧 >[LeetCode] 406. Queue Reconstruction by Height(按身高重排佇列)

[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()
    }
}