zoukankan      html  css  js  c++  java
  • [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()
        }
    }
    
  • 相关阅读:
    hihocoder #1388 : Periodic Signal NTT&FFT
    HDU 5895 Mathematician QSC(矩阵乘法+循环节降幂+除法取模小技巧+快速幂)
    hdu 5894 hannnnah_j’s Biological Test 组合数学
    csu 1812: 三角形和矩形 凸包
    地铁 Dijkstra(优先队列优化) 湖南省第12届省赛
    后缀自动机专题
    数学渣的自我修养!!!
    高斯消元(浮点)
    The PLAN
    ccpc网络赛
  • 原文地址:https://www.cnblogs.com/zhongju/p/13877914.html
Copyright © 2011-2022 走看看