Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
双指针!
public class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result=new ArrayList<List<Integer>>();
for(int i=0;i<nums.length-2&&nums[i]<=0;i++){
if(i>0 && nums[i]==nums[i-1])continue;
int l=i+1;
int r=nums.length-1;
while(l<r){
int sum=nums[l]+nums[i]+nums[r];
if(sum==0){
List<Integer> list=new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
result.add(list);
l++;
r--;
while(l<r&&nums[l]==nums[l-1]) l++;
while(l<r&&nums[r]==nums[r+1]) r--;
}else if(sum>0){
r--;
}else{
l++;
}
}
}
return result;
}
}
本文探讨了经典的三数之和为零问题,并提供了一种有效的解决方案——使用双指针算法来查找数组中所有不重复的三元组,使得它们的总和等于零。通过先对数组进行排序,然后迭代并利用双指针技巧来避免重复解。
250

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



