406. Queue Reconstruction by Height

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

首先,我们找到最小的 height (h, k),这个数据对的最终位置应该是在 k + 1 的位置上。因为这个值是最小的值,所以其它的值就不小于它。 如果它不在 k + 1 这个位置上,比如在 k + 1 + 1 这个位置上,那么它就应该是 (h, k + 1),因为它前面有 k + 1 个数是大于等于它的。

然后,我们看一下次小的值。因为在最终位置上的数都是小于它的,所以最终结果表上的那些数据对它的 k 值是没有影响的,我们只需要把次小的 height 数值对放在余下的空的第 k + 1 的位置上就行了。

例子:

输入: [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
排序之后: [[4, 4], [5, 0], [5, 2], [6, 1], [7, 0], [7, 1]]

1. [None, None, None, None, [4, 4], None]
2. [[5, 0], None, None, None, [4, 4], None]
3. [[5, 0], None, [5, 2], None, [4, 4], None]
4. [[5, 0], None, [5, 2], [6, 1], [4, 4], None]
5. [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], None]
6. [[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]]
        """
        people.sort()

        n = len(people)
        table = [i for i in range(n)] # store the final positions
        res = [None] * n

        while people:
            top = people.pop(0)
            stack = [top]
            # find the same height
            while people and people[0][0] == stack[0][0]:
                stack.append(people.pop(0))

            # put them in the final position
            while stack:
                top = stack.pop()
                idx = top[1]
                res[table.pop(idx)] = top # put in the final position


        return res

results matching ""

    No results matching ""