1. 程式人生 > >[Leetcode] 406. Queue Reconstruction by Height 直覺解釋

[Leetcode] 406. Queue Reconstruction by Height 直覺解釋

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