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()
        }
    }
    
  • 相关阅读:
    LFU
    poj 3581 -- 后缀数组
    leetcode 679
    poj 两条线段接雨水
    poj 1696极角排序
    判断平面上是否有一条直线与所有线段相交
    洛谷P3808 【模板】AC自动机(简单版)
    Most Distant Point from the Sea UVA
    P2742 [USACO5.1]圈奶牛Fencing the Cows /【模板】二维凸包
    P2249
  • 原文地址:https://www.cnblogs.com/zhongju/p/13877914.html
Copyright © 2011-2022 走看看