码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-10-27 10:54:44      阅读:28      评论:0      收藏:0      [点我收藏+]

标签:less   随机   Fix   related   https   int   greedy   lang   list   

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(按身高重排队列)

标签:less   随机   Fix   related   https   int   greedy   lang   list   

原文地址:https://www.cnblogs.com/zhongju/p/13877914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!