15 3Sum
Given an arraynums
ofn_integers, are there elements_a,b,c_innums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
class Solution {
//[0,0,0,0,0,0,0,0]
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length < 3) {
return ans;
}
Arrays.sort(nums);
int len = nums.length;
for (int i = 0; i < len; i++) {
if (i >= 1) {
if (nums[i] ==nums[i - 1]){
continue;
}
}
if (nums[i] > 0) {
break;
}
int left = i + 1;
int right = nums.length - 1;
int target = -nums[i];
find2sum(nums, ans, left, right, target);
}
return ans;
}
private void find2sum(int[] nums, List<List<Integer>> ans, int left, int right, int target) {
while (left < right) {
if (nums[left] + nums[right] == target) {
List<Integer> triple = new ArrayList<>();
triple.add(-target);
triple.add(nums[left]);
triple.add(nums[right]);
ans.add(triple);
left++;
right--;
while(left < right && nums[left] == nums[left - 1]) {
left++;
}
while(left < right && nums[right] == nums[right + 1]) {
right--;
}
}else if (nums[left] + nums[right] > target){
right--;
}else{
left++;
}
}
}
}