根据身高重建队列
拟人算法系列文章,以容易理解的方式描述算法,点赞收藏不迷路
class Solution:
def reconstructQueue(self, people: list[list[int]]) -> list[list[int]]:
res: list[list[int]] = []
people = sorted(people, key=lambda x: (-x[0], x[1]))
# [[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
for p in people:
if len(res) <= p[1]:
res.append(p)
else:
res.insert(p[1], p)
return res
if __name__ == '__main__':
s = Solution()
people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]
print(s.reconstructQueue(people))
# [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
首先对这些人按元素一降序排序(身高),按元素二升序排序(前面身高大于等于自己的人数),然后
- 如果队列长度小于等于这个人前面的人数,那么 append
- 否则插入到它代表的位置