1. 程式人生 > >python leetcode 406. Queue Reconstruction by Height

python leetcode 406. Queue Reconstruction by Height

要儘量保證大的h在後面 所以進行如下
people = sorted(people, key=lambda people:(-people[0],people[1])) h降序 k降序
再遍歷進行插入操作,插入位置為people[i][1]能保證符合題意 舉例說明
people=[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
people = sorted(people, key=lambda people:(-people[0],people[1]))
此時people=[[7, 0], [7, 1], [6, 1], [5, 0], [5, 2], [4, 4]]
迴圈時res結果
[[7, 0]]
[[7, 0], [7, 1]]
[[7, 0],[6, 1], [7, 1]]
[[5, 0], [7, 0],[6, 1], [7, 1]]
[[5, 0], [7, 0],[5, 2],[6, 1], [7, 1]]
[[5, 0], [7, 0],[5, 2],[6, 1], [4, 4],[7, 1]]

class Solution(object):
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """
        if people ==[]:
            return []
        people = sorted(people, key=lambda people:(-people[0],people[1]))
        res=[people[0]]
        for i in range(1,len(people)):
            res.insert(people[i][1],people[i])
        return res