leetcode刷題記錄421-430 python版

前言

繼續leetcode刷題生涯
這裏記錄的都是筆者覺得有點意思的做法
參考了好幾位大佬的題解,尤其是powcai大佬和labuladong大佬,感謝各位大佬

421. 數組中兩個數的最大異或值

# 貪心
class Solution:
    def findMaximumXOR(self, nums: List[int]) -> int:
        res, mask = 0, 0
        for i in range(31, -1, -1):
            mask = mask | (1<<i) #從高位開始的掩碼
            s = set()
            for num in nums:
                s.add(num & mask)
            tmp = res | (1<<i)
            for j in s:
                if tmp ^ j in s:
                    res = tmp
                    break
        return res

423. 從英文中重建數字

# 找規律
class Solution:
    def originalDigits(self, s: str) -> str:
        import collections
        s = collections.Counter(s) 
        zero = s["z"]
        two = s["w"]
        four = s["u"]
        six = s["x"]
        eight = s["g"]
        one = s["o"] - zero - two - four
        three = s["t"] - eight - two
        five = s["f"] - four
        seven = s["s"] - six
        nine = s["i"] - six - eight - five
        res = ""
        for idx, val in enumerate([zero, one, two, three, four, five, six, seven, eight, nine]):
            res += str(idx) * val
        return res

424. 替換後的最長重複字符

# 滑動窗口
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        if s is None or len(s) == 0: return 0
        from collections import Counter
        res = 0
        dic = Counter()
        max_len = 0
        for i in range(len(s)):
            dic[s[i]] += 1
            max_len = max(max_len, dic[s[i]])
            if res - max_len < k:
                res += 1
            else:
                dic[s[i-res]] -= 1
        return res
# 滑動窗口
class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        if s is None or len(s) == 0: return 0
        from collections import defaultdict
        hash = defaultdict(int)
        left = 0
        res = 0
        for right, val in enumerate(s):
            hash[val] += 1
            # 注意這裏爲什麼是while循環,舉個特列 AABCD K=1,左指針必須移動到條件r-l+1不大於K
            while right - left + 1 - max(hash.values()) > k:
                hash[s[left]] -= 1
                left += 1
                # 這裏只找滿足條件的最大值,當大於maxcount的值出現,表示right-left+1的值更大
            res = max(right - left + 1, res)
        return res

427. 建立四叉樹

# 遞歸
class Solution:
    def construct(self, grid: List[List[int]]) -> 'Node':
        import numpy as np
        grid = np.array(grid)
        def is_leaf(grid, row, col):
            return all(grid[i][j] == grid[0][0] for i in range(row) for j in range(col))
        def dfs(grid):
            row = len(grid)
            col = len(grid[0])
            if is_leaf(grid, row, col):
                return Node(
                    grid[0][0] == 1,
                    True,
                    None, None, None, None
                )
            root = Node(
                "*", False, None, None, None, None
            )
            root.topLeft = dfs(grid[:row // 2, :col // 2])
            root.topRight = dfs(grid[:row // 2, col // 2:])
            root.bottomLeft = dfs(grid[row // 2:, :col // 2])
            root.bottomRight = dfs(grid[row // 2:, col // 2:])
            return root
        return dfs(grid)

429. N叉樹的層序遍歷

# dfs
class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        res = []
        def dfs(root, depth):
            if not root: return
            if len(res) <= depth:
                res.append([])
            res[depth].append(root.val)
            for ch in root.children:
                dfs(ch, depth + 1)
        dfs(root, 0)
        return res
# bfs
class Solution:
    def levelOrder(self, root: 'Node') -> List[List[int]]:
        if not root: return []
        res = []
        def bfs(root):
            queue = [root]
            while queue:
                nxt = []
                tmp = []
                for node in queue:
                    tmp.append(node.val)
                    for ch in node.children:
                        nxt.append(ch)
                res.append(tmp)
                queue = nxt
        bfs(root)
        return res

430. 扁平化多級雙向鏈表

# 遞歸
class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        if not head: return
        dummy = Node(-1, None, None, None)
        p = dummy
        def dfs(pre, head):
            if not head:
                return pre
            head.prev = pre
            pre.next = head
            # 記錄下一個節點
            tmpNext = head.next
            # 返回尾節點
            tail = dfs(head, head.child)
            head.child = None
            return dfs(tail, tmpNext)
        dfs(dummy, head)
        p.next.prev = None
        return p.next
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章