假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
示例
输入:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
输出:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
由于是看前面有几个升高更高的,所以我们需要按照身高由高到低排序。
然后再项结果队列中一个一个插入元素。在插入某个人时比起高的人都在队列中,
避免了不确定性。
from typing import *
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
#将所有人到倒序排列
people.sort(key=lambda x:(-x[0], x[1]))
ans=[]
for person in people:
ans.insert(person[1],person)
return ans