《算法面试必刷:15 个高频 LeetCode 题(附代码)》

《算法面试必刷:15 个高频 LeetCode 题(附代码)》

在算法面试中,掌握高频题目是提升竞争力的关键。LeetCode 平台上的高频题常考察数据结构、算法设计和优化能力。以下是我为您整理的15个高频 LeetCode 题(基于真实面试数据),每个题包括题目描述、解题思路和代码实现(使用 Python)。代码确保简洁高效,时间复杂度分析使用数学表达式表示(如 O(n))。所有内容基于常见面试题,真实可靠。

1. 两数之和 (Two Sum)
  • 题目描述 :给定一个整数数组 nums 和一个目标值 target,在数组中找出和为目标值的两个整数,并返回它们的索引。
  • 解题思路:使用哈希表存储元素和索引,遍历数组时检查差值是否存在。时间复杂度为 O(n),空间复杂度为 O(n)
python 复制代码
def two_sum(nums, target):
    hash_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_map:
            return [hash_map[complement], i]
        hash_map[num] = i
    return []
2. 反转链表 (Reverse Linked List)
  • 题目描述:给定一个单链表的头节点,反转链表并返回反转后的头节点。
  • 解题思路:使用迭代法,维护三个指针(prev, current, next)逐步反转。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverse_list(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev
3. 有效的括号 (Valid Parentheses)
  • 题目描述 :给定一个只包含 '(', ')', '{', '}', '[', ']' 的字符串,判断字符串是否有效(即括号正确匹配)。
  • 解题思路:使用栈存储左括号,遇到右括号时检查栈顶是否匹配。时间复杂度为 O(n),空间复杂度为 O(n)
python 复制代码
def is_valid(s):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}
    for char in s:
        if char in mapping:
            top_element = stack.pop() if stack else '#'
            if mapping[char] != top_element:
                return False
        else:
            stack.append(char)
    return not stack
4. 二叉树的层序遍历 (Binary Tree Level Order Traversal)
  • 题目描述:给定一个二叉树的根节点,返回其节点值的层序遍历结果(即逐层从左到右)。
  • 解题思路:使用队列进行广度优先搜索(BFS)。时间复杂度为 O(n),空间复杂度为 O(n)
python 复制代码
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def level_order(root):
    if not root:
        return []
    result = []
    queue = [root]
    while queue:
        level = []
        for _ in range(len(queue)):
            node = queue.pop(0)
            level.append(node.val)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        result.append(level)
    return result
5. 最大子数组和 (Maximum Subarray)
  • 题目描述 :给定一个整数数组 nums,找出具有最大和的连续子数组,并返回其和。
  • 解题思路:使用动态规划(Kadane 算法),维护当前和与最大和。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
def max_subarray(nums):
    max_current = max_global = nums[0]
    for i in range(1, len(nums)):
        max_current = max(nums[i], max_current + nums[i])
        if max_current > max_global:
            max_global = max_current
    return max_global
6. 合并两个有序链表 (Merge Two Sorted Lists)
  • 题目描述:给定两个升序链表,合并为一个新链表并返回头节点。
  • 解题思路:使用迭代法,比较节点值并连接。时间复杂度为 O(n + m),空间复杂度为 O(1)
python 复制代码
def merge_two_lists(l1, l2):
    dummy = ListNode()
    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
7. 爬楼梯 (Climbing Stairs)
  • 题目描述 :假设你正在爬楼梯,每次可以爬1或2阶,计算爬到第 n 阶有多少种不同方式。
  • 解题思路:使用动态规划,状态转移方程为 dp\[i\] = dp\[i-1\] + dp\[i-2\]。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
def climb_stairs(n):
    if n == 1:
        return 1
    a, b = 1, 2
    for _ in range(2, n):
        a, b = b, a + b
    return b
8. 买卖股票的最佳时机 (Best Time to Buy and Sell Stock)
  • 题目描述 :给定一个数组 prices,其中 prices[i] 是股票第 i 天的价格,计算只允许一次交易的最大利润。
  • 解题思路:遍历数组,维护最小价格和最大利润。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
def max_profit(prices):
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        if price < min_price:
            min_price = price
        elif price - min_price > max_profit:
            max_profit = price - min_price
    return max_profit
9. 无重复字符的最长子串 (Longest Substring Without Repeating Characters)
  • 题目描述:给定一个字符串,找出不包含重复字符的最长子串的长度。
  • 解题思路:使用滑动窗口和哈希表记录字符索引。时间复杂度为 O(n),空间复杂度为 O(k)k 为字符集大小)。
python 复制代码
def length_of_longest_substring(s):
    char_index = {}
    left = 0
    max_length = 0
    for right, char in enumerate(s):
        if char in char_index and char_index[char] >= left:
            left = char_index[char] + 1
        char_index[char] = right
        max_length = max(max_length, right - left + 1)
    return max_length
10. 字符串转换整数 (atoi) (String to Integer (atoi))
  • 题目描述 :实现一个函数,将字符串转换为整数(类似 C 语言的 atoi 函数),处理空格、符号和溢出。
  • 解题思路:遍历字符串,解析数字并检查边界。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
def my_atoi(s):
    s = s.strip()
    if not s:
        return 0
    sign = 1
    if s[0] in ['-', '+']:
        if s[0] == '-':
            sign = -1
        s = s[1:]
    num = 0
    for char in s:
        if not char.isdigit():
            break
        num = num * 10 + int(char)
    num *= sign
    num = max(min(num, 2**31 - 1), -2**31)
    return num
11. 三数之和 (3Sum)
  • 题目描述 :给定一个整数数组,找出所有不重复的三元组 [nums[i], nums[j], nums[k]],使得 i != j != k 且和为0。
  • 解题思路:排序后使用双指针法。时间复杂度为 O(n\^2),空间复杂度为 O(1)
python 复制代码
def three_sum(nums):
    nums.sort()
    result = []
    for i in range(len(nums)):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                while left < right and nums[left] == nums[left + 1]:
                    left += 1
                while left < right and nums[right] == nums[right - 1]:
                    right -= 1
                left += 1
                right -= 1
    return result
12. 盛最多水的容器 (Container With Most Water)
  • 题目描述 :给定一个整数数组 height,其中 height[i] 是第 i 条垂直线的高度,找出两条线与 x 轴构成的容器能容纳的最大水量。
  • 解题思路:使用双指针从两端向中间移动,计算面积。时间复杂度为 O(n),空间复杂度为 O(1)
python 复制代码
def max_area(height):
    left, right = 0, len(height) - 1
    max_area = 0
    while left < right:
        h = min(height[left], height[right])
        w = right - left
        max_area = max(max_area, h * w)
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return max_area
13. 括号生成 (Generate Parentheses)
  • 题目描述 :给定一个整数 n,生成所有有效的由 n 对括号组成的字符串组合。
  • 解题思路:使用回溯法,递归生成括号序列。时间复杂度为 O(4\^n / \\sqrt{n}),空间复杂度为 O(n)
python 复制代码
def generate_parenthesis(n):
    def backtrack(s, left, right):
        if len(s) == 2 * n:
            result.append(s)
            return
        if left < n:
            backtrack(s + '(', left + 1, right)
        if right < left:
            backtrack(s + ')', left, right + 1)
    result = []
    backtrack('', 0, 0)
    return result
14. 电话号码的字母组合 (Letter Combinations of a Phone Number)
  • 题目描述:给定一个数字字符串(如 "23"),返回所有可能的字母组合(数字对应手机键盘字母)。
  • 解题思路:使用回溯法生成组合。时间复杂度为 O(3\^m \\times 4\^n)mn 为数字对应字母数),空间复杂度为 O(n)
python 复制代码
def letter_combinations(digits):
    if not digits:
        return []
    mapping = {
        '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
        '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
    }
    result = []
    def backtrack(combination, next_digits):
        if not next_digits:
            result.append(combination)
            return
        for letter in mapping[next_digits[0]]:
            backtrack(combination + letter, next_digits[1:])
    backtrack('', digits)
    return result
15. 全排列 (Permutations)
  • 题目描述:给定一个不含重复数字的数组,返回所有可能的全排列。
  • 解题思路:使用回溯法交换元素生成排列。时间复杂度为 O(n!),空间复杂度为 O(n)
python 复制代码
def permute(nums):
    def backtrack(start):
        if start == len(nums):
            result.append(nums[:])
            return
        for i in range(start, len(nums)):
            nums[start], nums[i] = nums[i], nums[start]
            backtrack(start + 1)
            nums[start], nums[i] = nums[i], nums[start]
    result = []
    backtrack(0)
    return result

总结

以上15个高频 LeetCode 题覆盖了数组、链表、字符串、树、动态规划、回溯等核心算法主题。掌握这些题能显著提升算法面试成功率。建议您:

  • 理解每个题的解题思路,避免死记硬背。
  • 在 LeetCode 平台实践,测试边界条件。
  • 扩展学习类似题目,如"四数之和"或"子集问题"。 如果您有具体题目或细节疑问,欢迎随时提问!
相关推荐
_深海凉_1 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
张槊哲2 小时前
C++ 进阶指南:如何丝滑地理解与实践多线程与多进程
开发语言·c++·算法
walking9572 小时前
重新学习前端之设计模式与架构
前端·javascript·面试
walking9572 小时前
重新学习前端之TypeScript
前端·javascript·面试
walking9572 小时前
重新学习前端之Linux
前端·vue.js·面试
walking9572 小时前
重新学习前端之CSS
前端·vue.js·面试
walking9572 小时前
重新学习前端之Git
前端·vue.js·面试
代码中介商2 小时前
C语言链表完全指南:从单节点到链表管理
c语言·算法·链表
小小de风呀3 小时前
de风——【从零开始学C++】(四):类和对象(下)
开发语言·c++·算法