LeetCode每日一题8月记录

LeetCode每日一题8月记录

  • 8.1 最小区间
  • 8.2 二叉树展开为链表

8.1 最小区间

原题地址.
变相的用滑动窗口法求解,统计每个数字出现在输入的哪几个数组里面,然后利用双指针滑动窗口寻找最小的左右边界,使得全部数组都有这些元素。

class Solution:
    def smallestRange(self, nums: List[List[int]]) -> List[int]:
        n = len(nums)
        indices = collections.defaultdict(list)
        xMin, xMax = 10**9, -10**9
        for i, vec in enumerate(nums):
            for x in vec:
                indices[x].append(i)
            xMin = min(xMin, *vec)
            xMax = max(xMax, *vec)

        freq = [0] * n
        inside = 0
        left, right = xMin, xMin - 1
        bestLeft, bestRight = xMin, xMax

        while right < xMax:
            right += 1
            if right in indices:
                #新加入统计右边界元素出现的list
                for x in indices[right]:
                    freq[x] += 1
                    #首次出现计数
                    if freq[x] == 1:
                        inside += 1
                while inside == n:
                    if right - left < bestRight - bestLeft:
                        bestLeft, bestRight = left, right
                    if left in indices:
                        for x in indices[left]:
                            freq[x] -= 1
                            #减到0推出窗口
                            if freq[x] == 0:
                                inside -= 1
                    left += 1

        return [bestLeft, bestRight]

8.2 二叉树展开为链表

原题地址.
递归处理,每次把左子树交换到右子树,把原来的右子树摘出来挂到左子树的最右儿子上,再处理下一层树。

class Solution:
    def flatten(self, root: TreeNode) -> None:
        if not root:
            return
        temp = root.right
        root.right = root.left
        root.left = None
        curr = root
        while curr.right:
            curr = curr.right
        curr.right = temp
        if root.right:
            self.flatten(root.right)
        return

你可能感兴趣的:(LeetCode,leetcode,算法,数据结构)