406. Queue Reconstruction by Height
- Queue Reconstruction by Height python solution
题目描述
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.
Note:
The number of people is less than 1,100.
解析
向大佬学习了。
首先将people按降序排列,对应语句是people=sorted(people,key=lambda x:(-x[0],x[1]))
people_sorted = [[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]]
sorted(people,key=lambda x:(-x[0],x[1])),先按第一维属性降序排列,如果相同再按第二维属性升序排列。
然后
[[7,0]] (insert [7,0] at index 0)
[[7,0],[7,1]] (insert [7,1] at index 1)
[[7,0],[6,1],[7,1]] (insert [6,1] at index 1)
[[5,0],[7,0],[6,1],[7,1]] (insert [5,0] at index 0)
[[5,0],[7,0],[5,2],[6,1],[7,1]] (insert [5,2] at index 2)
[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] (insert [4,4] at index 4)
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
people=sorted(people,key=lambda x:(-x[0],x[1]))
res=[]
for p in people:
res.insert(p[1],p)
return res
Reference
https://leetcode.com/problems/queue-reconstruction-by-height/discuss/167308/Python-solution