题目:
假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(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]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
方法一:
- 用哈希表记录每个身高的k值;
- 首先将最高的取出按期k值插入队列,因为此时最高的前面的个数是只取决于其同等身高的人,跟其它人高的人无关;
- 同理,依次将剩余的人中最高人高的人取出插入到队列中去。
class Solution:
def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
count = {}
h_list = []
for (h, k) in people:
if h not in count:
count[h] = [k]
h_list.append(h)
else:
count[h].append(k)
h_list.sort(reverse=True)
reuslt=[]
for h in h_list:
count[h].sort()
for k in count[h]:
reuslt.insert(k, [h, k])
return reuslt