public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i = 0; i < nums.length2; i++) {
if(i > 0 && (nums[i] == nums[i1])) continue; // avoid duplicates
for(int j = i+1, k = nums.length1; j<k;) {
if(nums[i] + nums[j] + nums[k] == 0) {
list.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++;k;
while((j < k) && (nums[j] == nums[j1]))j++;// avoid duplicates
while((j < k) && (nums[k] == nums[k+1]))k;// avoid duplicates
}else if(nums[i] + nums[j] + nums[k] > 0) k;
else j++;
}
}
return list;
}
Simple Java Solution  Without using Hash/Set


The idea here is to sort the array first. Then for each element(
i
), have two pointers at the beginning(j
), and end(k
). Check if 3sum == 0.To avoid duplicates, if any of the next number is same, just skip it. That is, if
nums[i]
is same as previous, skip it. Similarly fornums[j]
andnums[k]