LeetCode图解 3Sum & Array类型问题
LeetCode图解 3Sum & Array类型问题
1.问题描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
2.测试用例
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
3.提示
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
4.解题思路
一、暴力
public List<List<Integer>> threeSum1(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
return res;
}
问题:
- 未能去重,去重逻辑复杂
- 时间复杂度高,能达到O(n^3)
二、hash
参考两数相加的思路,可以利用hash,来改进暴力复杂度过高的问题
public List<List<Integer>> threeSum2(int[] nums) {
int n = nums.length;
List<List<Integer>> result = new ArrayList<>();
Map<Integer, List<Integer>> hashMap = new HashMap<>();
// 遍历数组,寻找每个元素的thatNum
for (int i = 0; i < n; i++) {
int thatNum = 0 - nums[i];
if (hashMap.containsKey(thatNum)) {
List<Integer> tempList = new ArrayList<>(
hashMap.get(thatNum));
tempList.add(nums[i]);
result.add(tempList);
continue;
}
for (int j = 0; j < i; j++) {
int newKey = nums[i] + nums[j];
if (!hashMap.containsKey(newKey)) {
List<Integer> tempList = new ArrayList<>();
tempList.add(nums[j]);
tempList.add(nums[i]);
hashMap.put(newKey, tempList);
}
}
}
return result;
}
问题:
- 可以hold住大部分的问题,当输入是[0,0,0,0],会出现重复数据,去重不完全,并不完美
三、双指针
public List<List<Integer>> threeSumFinal(int[] nums) {
int n = nums.length;
ArrayList<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int p0 = 0; p0 < n; p0++) {
//左指针
int pl = p0 + 1;
//有指针
int pr = n - 1;
//结束循环
if (nums[p0] > 0) {
break;
}
//前面有匹配过相同的p0后面就不再匹配
if (p0 > 0 && nums[p0] == nums[p0 - 1]) {
continue;
}
while (pl < pr) {
int sum = nums[p0] + nums[pl] + nums[pr];
if (sum == 0) {
result.add(Arrays.asList(nums[p0], nums[pl], nums[pr]));
pl++;
pr--;
//相同跳过
while (pl < pr && nums[pl] == nums[pl - 1]) {
pl++;
}
//相同跳过
while (pl < pr && nums[pr] == nums[pr + 1]) {
pr--;
}
} else if (sum < 0) {
pl++;
} else {
pr--;
}
}
}
return result;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)