前言
继续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