美文网首页
排队问题

排队问题

作者: 拔丝圣代 | 来源:发表于2017-12-15 00:06 被阅读0次

    排队问题


    已知每个人的身高 h,他前面身高大于等于他的人数为 k,给这些人排队,求这些人的顺序。

    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]]
    

    思路:

    高个先排,后面逐渐插队,同样身高的先插前面的,每个人插队时,k就是要插入的位置的下标。
    代码:

    class Solution(object):
        def reconstructQueue(self, people):
            """
            :type people: List[List[int]]
            :rtype: List[List[int]]
            """
            l = len(people)
            result = []
            people.sort(key=lambda x: (-x[0], x[1]))
            for h, k in people:
                result.insert(k, [h,k])
            return result
    

    相关文章

      网友评论

          本文标题:排队问题

          本文链接:https://www.haomeiwen.com/subject/hnfgixtx.html