LeetCode | 0406. Queue Reconstruction by Height根據身高重建隊列【Python】

LeetCode 0406. Queue Reconstruction by Height根據身高重建隊列【Medium】【Python】【貪心】

Problem

LeetCodepython

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (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.git

Note:
The number of people is less than 1,100.github

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]]

問題

力扣less

假設有打亂順序的一羣人站成一個隊列。 每一個人由一個整數對 (h, k) 表示,其中 h 是這我的的身高,k 是排在這我的前面且身高大於或等於 h 的人數。 編寫一個算法來重建這個隊列。dom

注意:
總人數少於1100人。this

示例code

輸入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

輸出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

思路

貪心排序

首先按照身高 h 從高到低,k 從小到大排序。隊列

而後只需插入便可,能夠看代碼註釋。

這裏拿示例來舉例:

輸入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

排序:
[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]

好比[6,1],表示前面比 6 高的只有一個,那麼天然就插入到位置1(從0開始數):
[[7,0], [6,1], [7,1], [5,0], [5,2], [4,4]]

以此類推

[5,0]:
[[5,0], [7,0], [6,1], [7,1], [5,2], [4,4]]

[5,2]:
[[5,0], [7,0], [5,2], [6,1], [7,1], [4,4]]

[4,4]:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

end

時間複雜度: O(len(people))
空間複雜度: O(1)

Python代碼

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        people.sort(key = lambda x : (-x[0], x[1]))  # 按照h從高到低,k從小到大排序
        res = []
        for p in people:
            res.insert(p[1], p)  # 每次只要在p[1]位置插入p就行,由於p[1]表示p前只能出現的個數
        return res

代碼地址

GitHub連接

相關文章
相關標籤/搜索