LeetCode 0406. Queue Reconstruction by Height根据身高重建队列【Medium】【Python】【贪心】
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)
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