15. 3Sum
Given an array nums of n integers, are there elements a, b, c
in nums 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.
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>();
for(int i = 0; i < nums.length - 2; i++) {
if(i > 0 && nums[i] == nums[i-1]) continue; // remove duplicate
int l = i + 1, r = nums.length-1;
while(l < r) {
if(l > i+1 && nums[l] == nums[l-1]) { // remove duplicate
l++;
continue;
}
if(nums[l] + nums[r] + nums[i] == 0) {
result.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[l], nums[r])));
l++;
r--;
} else if(nums[l] + nums[r] + nums[i] < 0) {
l++;
} else {
r--;
}
}
}
return result;
}