知序
返回
保存草稿
发布
H1
H2
H3
1
2
3
Excalidraw 图
AI 写作
AI 优化
目录
输入内容后显示目录
Markdown
# 06 - 三数之和 ## 题目(LeetCode 15) 找出数组中所有和为 0 的三元组,不能重复。 ## 解法:排序 + 双指针 ```java class Solution { public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i < nums.length - 2; i++) { if (nums[i] > 0) break; if (i > 0 && nums[i] == nums[i - 1]) continue; // 去重 int left = i + 1, right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (sum == 0) { res.add(Arrays.asList(nums[i], nums[left], nums[right])); while (left < right && nums[left] == nums[left + 1]) left++; while (left < right && nums[right] == nums[right - 1]) right--; left++; right--; } else if (sum < 0) left++; else right--; } } return res; } } ``` ## 复杂度 - 时间 O(n²),空间 O(1)(不算结果) ## 一句话总结 排序后固定一个数,剩下两个用双指针找,注意三处去重。 ## 解法二:哈希集合 固定前两个数,用 HashSet 查找第三个数。去重逻辑更复杂,实际不如双指针。 ```java class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); Set<List<Integer>> res = new HashSet<>(); for (int i = 0; i < nums.length - 2; i++) { if (nums[i] > 0) break; Set<Integer> seen = new HashSet<>(); for (int j = i + 1; j < nums.length; j++) { int need = -nums[i] - nums[j]; if (seen.contains(need)) { res.add(Arrays.asList(nums[i], need, nums[j])); } seen.add(nums[j]); } } return new ArrayList<>(res); } } ``` ## 解法对比 | | 解法一(双指针) | 解法二(哈希集合) | |--|--------|--------| | 时间复杂度 | O(n²) | O(n²) | | 空间复杂度 | O(1) | O(n) | | 特点 | 去重简洁,推荐 | 去重依赖 Set,常数大 |
预览
发布文章
添加摘要让读者更快了解文章内容
取消
确认发布
AI 写作助手
输入一个主题,AI 将为你生成一篇 Markdown 博客文章
AI 正在写作中...
取消
开始生成
AI 优化助手
描述你的修改需求,AI 将在原文基础上进行补充或微调
AI 正在优化中...
取消
开始优化
画布
从已有图里选
✕
图名
保存后生成 /images/excalidraw/<图名>.svg(只能用字母、数字、短横线、下划线、点)
取消
保存并插入