class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> rs=new ArrayList<>();
if(nums==null||nums.length<3){
return rs;
}
Arrays.sort(nums);
// 对每个元素,对他后面的子数组做一个双指针的查找,看有没有和为0
for(int i=0;i<nums.length-2;i++){
// 对于已经大于0的,因为是升序,所以后面不可能使其和为0
if(nums[i]>0){
break;
}
// 去掉重复解
if(i>0&&nums[i]==nums[i-1]){
continue;
}
int lo=i+1,hi=nums.length-1;
while(lo<hi){
int s=nums[i]+nums[lo]+nums[hi];
if(s==0){
rs.add(Arrays.asList(new Integer[]{nums[i],nums[lo],nums[hi]}));
int t=nums[lo];
while(lo<hi&&nums[lo]==t){
lo++;
}
t=nums[hi];
while(lo<hi&&nums[hi]==t){
hi--;
}
}else if(s<0){
lo++;
}else if(s>0){
hi--;
}
}
}
return rs;
}
}
(感觉有些题答案都记得了 但是很多不是很能说出个所以然来
该博客介绍了如何通过排序和双指针算法解决寻找数组中三数之和为0的子集问题。代码实现了一个Java方法,首先对输入数组进行排序,然后遍历数组并使用双指针技术检查后续元素的组合,找到所有可能的解。这种方法避免了重复解,并且在找到大于0的元素时提前结束,提高了效率。
603

被折叠的 条评论
为什么被折叠?



