前言
学习方法
- 首先学习算法主要思想
- 然后背过算法模板并做题目(尤其是涉及边界问题的算法最好背过模板)
- 提高熟练度-题目反复做,做完删掉重新做,做3-5遍
方法思路总结
如何选择数据结构
考虑什么时候用什么数据结构的时候(所有的数据结构问题),先去看一下题目当中的哪些操作可以进行优化,操作有什么样的特点
- 比如说要寻找一堆数里面的最小值或最大值时——用堆
- 当我们想去维护一个有序链表的时候,要用平衡树set来做
- 让我们想去维护区间最大值、区间和,可能要用树状数组,线性树
调试出现错误答案
- 输出中间结果法
- 删代码法:出现RE或者SF错误,就用删代码法,一块代码一块代码的删,如果SF不再出现,就是哪部分代码的问题。
- 如果数组越界了,则什么错误都可能发生。
动态规划
- 当题目涉及到 f[i - 1] 下标时,i要从1开始,否则从0开始。
- 动态规划的时间复杂度一般等于,状态数量 * 转移的计算量
- 状态表示维数选择,在答案能够表示且能推出来的前提下,维数越小越好,一般是从小往大考虑。(维数越大,时间复杂度越高)
一、LeetCode入门:Python基础设置
1.1 Python环境配置
在开始LeetCode之前,确保你的Python环境配置正确:
# 推荐使用Python 3.6+版本
import sys
print(sys.version)
# 安装常用库
# pip install numpy pandas matplotlib # 虽然LeetCode不需要这些,但数据科学问题可能有用
1.2 LeetCode Python模板
理解LeetCode的输入输出处理方式:
class Solution:
def problemName(self, parameters) -> returnType:
# 你的解决方案
pass
# 示例:两数之和
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_map = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
二、Python刷题核心技巧
2.1 常用数据结构实现
2.1.1 列表(List)的高级用法
# 列表推导式
squares = [x**2 for x in range(10) if x % 2 == 0]
# 切片操作
nums = [1, 2, 3, 4, 5]
reverse_nums = nums[::-1] # 反转列表
# 扁平化二维列表
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [num for row in matrix for num in row]
2.1.2 字典(Dict)的妙用
# 默认字典
from collections import defaultdict
word_count = defaultdict(int)
# 计数器
from collections import Counter
count = Counter("leetcode") # Counter({'e': 3, 'l': 1, 't': 1, 'c': 1, 'o': 1, 'd': 1})
# 字典推导式
square_dict = {x: x*x for x in range(5)}
2.2 Python内置函数优化
# 排序与lambda函数
points = [(1, 2), (3, 4), (0, 1)]
points.sort(key=lambda x: x[0]**2 + x[1]**2)
# 使用zip处理多个列表
names = ['Alice', 'Bob', 'Charlie']
scores = [95, 87, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# any和all函数
nums = [1, 3, 5, 7, 9]
has_even = any(num % 2 == 0 for num in nums)
all_odd = all(num % 2 == 1 for num in nums)
三、算法专题突破
3.1 双指针技巧
3.1.1 快慢指针
# 链表中的环检测(LeetCode 141)
def hasCycle(head):
if not head or not head.next:
return False
slow, fast = head, head.next
while fast and fast.next:
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
3.1.2 左右指针
# 盛最多水的容器(LeetCode 11)
def maxArea(height):
left, right = 0, len(height) - 1
max_area = 0
while left < right:
current_area = min(height[left], height[right]) * (right - left)
max_area = max(max_area, current_area)
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
3.2 动态规划
3.2.1 经典DP问题
# 爬楼梯(LeetCode 70)
def climbStairs(n):
if n == 1:
return 1
dp = [0] * (n + 1)
dp[1], dp[2] = 1, 2
for i in range(3, n + 1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
# 优化空间复杂度为O(1)
def climbStairs_optimized(n):
if n == 1:
return 1
first, second = 1, 2
for _ in range(3, n + 1):
third = first + second
first, second = second, third
return second
3.2.2 背包问题
# 0-1背包问题
def knapsack(weights, values, capacity):
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(1, capacity + 1):
if weights[i-1] <= w:
dp[i][w] = max(values[i-1] + dp[i-1][w-weights[i-1]], dp[i-1][w])
else:
dp[i][w] = dp[i-1][w]
return dp[n][capacity]
3.3 回溯算法
# 全排列(LeetCode 46)
def permute(nums):
def backtrack(first=0):
if first == n:
output.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output
四、LeetCode高频题目分类解析
4.1 数组与字符串
4.1.1 滑动窗口
# 无重复字符的最长子串(LeetCode 3)
def lengthOfLongestSubstring(s):
char_map = {}
left = max_len = 0
for right, char in enumerate(s):
if char in char_map and char_map[char] >= left:
left = char_map[char] + 1
char_map[char] = right
max_len = max(max_len, right - left + 1)
return max_len
4.1.2 前缀和
# 和为K的子数组(LeetCode 560)
def subarraySum(nums, k):
prefix_sum = {0: 1}
current_sum = 0
count = 0
for num in nums:
current_sum += num
if current_sum - k in prefix_sum:
count += prefix_sum[current_sum - k]
prefix_sum[current_sum] = prefix_sum.get(current_sum, 0) + 1
return count
4.2 链表问题
# 反转链表(LeetCode 206)
def reverseList(head):
prev = None
current = head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev
# 合并两个有序链表(LeetCode 21)
def mergeTwoLists(l1, l2):
dummy = ListNode(-1)
current = dummy
while l1 and l2:
if l1.val < l2.val:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.next
current.next = l1 if l1 else l2
return dummy.next
五、面试技巧与策略
5.1 面试四步法
- 理解问题:确认输入输出,询问边界条件
- 提出方法:先给出暴力解法,再优化
- 编写代码:模块化,添加注释
- 测试验证:用测试用例验证代码
5.2 复杂度分析模板
"""
时间复杂度:O(n) - 解释为什么是这个复杂度
空间复杂度:O(1) - 解释空间使用情况
"""
5.3 常见问题回答模板
Q: 如何优化这个解法? A: "当前的解法时间复杂度是O(n^2),我们可以考虑使用哈希表来存储中间结果,将时间复杂度降低到O(n)..."
Python算法题
目前我们收集与整理了以下Python相关题目以及相应的答案,后面还会继续做调整