• [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()
        }
    }
    
  • 相关阅读:
    最新的Zynq资料整理
    异步FIFO的FPGA实现
    Mac 下安装PHP遇到的问题
    php 实现推技术comet(转)
    高性能分布式内存队列系统beanstalkd(转)
    应对Memcached缓存失效,导致高并发查询DB的四种思路(l转)
    memcache 缓存失效问题(转)
    PHP.ini文件读取不到
    PHP5中魔术方法
    python mysql 单引号字符串过滤
  • 原文地址:https://www.cnblogs.com/zhongju/p/13877914.html
Copyright © 2020-2023  润新知