Easy两数之和两数之和class Solution: def twoSum(self, nums: List[int], target: int) - List[int]: xdict{} for i in range(len(nums)): jtarget-nums[i] if j in xdict.keys(): return [i,xdict[j]] else: xdict[nums[i]]i有效的括号有效的括号class Solution: def isValid(self, s: str) - bool: map_dict{ ):(, }:{, ]:[, } st[] for item in s: if item not in map_dict.keys(): st.append(item) else: if not st: return False pop_itemst.pop() if pop_item!map_dict[item]: # 如果是嵌套括号的话不能交错嵌套。如果不是交错嵌套的内层的会正确被 pop 出来所以只需要 pop 最后的那个就可以了。 return False return not st合并两个有序链表合并两个有序链表# Definition for singly-linked list. # class ListNode: # def __init__(self, val0, nextNone): # self.val val # self.next next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) - Optional[ListNode]: # if not list1 and not list2: # return None currListNode() headcurr while list1 and list2: if list1.vallist2.val: curr.nextlist1 list1list1.next else: curr.nextlist2 list2list2.next currcurr.next if list1: curr.nextlist1 if list2: curr.nextlist2 return head.next爬楼梯爬楼梯class Solution: def climbStairs(self, n: int) - int: if n1: return 1 if n2: return 2 dp[0]*n dp[0]1 dp[1]2 for i in range(2,n): dp[i]dp[i-1]dp[i-2] return dp[n-1]二叉树的中序遍历二叉树的中序遍历# Definition for a binary tree node. # class TreeNode: # def __init__(self, val0, leftNone, rightNone): # self.val val # self.left left # self.right right class Solution: def inorderTraversal(self, root: Optional[TreeNode]) - List[int]: ret[] def dfs(node): if not node: return dfs(node.left) ret.append(node.val) dfs(node.right) dfs(root) return ret对称二叉树对称二叉树# Definition for a binary tree node. # class TreeNode: # def __init__(self, val0, leftNone, rightNone): # self.val val # self.left left # self.right right class Solution: def isSymmetric(self, root: Optional[TreeNode]) - bool: if not root: return True def search(t1,t2): if not t1 and not t2: return True if not t1 or not t2: return False return t1.valt2.val and search(t1.left,t2.right) and search(t1.right,t2.left) return search(root.left,root.right)二叉树的最大深度二叉树的最大深度# Definition for a binary tree node. # class TreeNode: # def __init__(self, val0, leftNone, rightNone): # self.val val # self.left left # self.right right class Solution: def maxDepth(self, root: Optional[TreeNode]) - int: if not root: return 0 left_depself.maxDepth(root.left) right_depself.maxDepth(root.right) return max(left_dep,right_dep)1 # 加一的根本原因是为了把当前节点所在的这一层计算进去。买卖股票的最佳时机买卖股票的最佳时机class Solution: def maxProfit(self, prices: List[int]) - int: max_ret0 min_costfloat(inf) nlen(prices) for i in range(1,n): min_costmin(min_cost,prices[i-1]) max_retmax(max_ret,prices[i]-min_cost) return max_ret