Leetcode精选50题-Day09
088 合并两个有序数组
1. 题目描述
2. 思路&代码
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
nums1[:] = sorted(nums1[:m]+nums2[:n])
复杂度分析
- 时间复杂度 : O ( ( n + m ) log ( n + m ) ) O((n + m)\log(n + m)) O((n+m)log(n+m))。
- 空间复杂度 : O ( 1 ) O(1) O(1)。
089 格雷编码
1. 题目描述
2. 思路&代码
class Solution:
def grayCode(self, n: int) -> List[int]:
seen = set([0])
def backtrack(path):
if len(path) == 2 ** n: return path
for i in range(n):
nxt = 1 << i ^ path[-1]
if nxt in seen: continue
seen.add(nxt)
path.append(nxt)
if backtrack(path): return path
path.pop()
seen.remove(nxt)
return backtrack([0])
104 二叉树的最大深度
1. 题目描述
2. 思路&代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
left_high = self.maxDepth(root.left)
right_high = self.maxDepth(root.right)
return max(left_high,right_high) + 1