[LeetCode] 394. Decode String

题:https://leetcode.com/problems/queue-reconstruction-by-height/description/

题目

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.

Example

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

思路

先将 peoples 排序,排序的 先 ele[0] 由大到小排序,若 ele[0] 相等 那么比较 ele[1]由小到大排序。

people 从大到小排序 ,放入 res中。
其对 原res是没有影响,只需要选好新ele 插入的位置,这里只需要根据 ele[1]的下标插入即可, 该下标显示了 新 ele 在res前有多少个元素,大于等于新ele。

Code

import functools
class Solution:
    def reconstructQueue(self, people):
        """
        :type people: List[List[int]]
        :rtype: List[List[int]]
        """

        people = sorted(people,key=functools.cmp_to_key(lambda x0, x1: x1[0] - x0[0]  or (x0[0] == x1[0] and x0[1] - x1[1])))

        res = []
        for ele in people:
            res.insert(ele[1], ele)
        return res

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82049731
今日推荐