3Sum(the fifteenth question of leetcode)
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.
Notice that the solution set must not contain duplicate triplets.
快速排序+双指针夹逼,注意相邻值相等时要跳过,否则方案重复
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int len = nums.length;
//从小到大排序
quickSort(nums, 0, nums.length - 1);
List<List<Integer>> result = new ArrayList<>();
//双指针找数
for(int i =0;i<len-2;i++){
if(nums[i]>0) return result;
if(i>0 && nums[i] == nums[i-1]) continue;
List<List<Integer>> temp = towSum(nums, i);
if(!temp.isEmpty()){
result.addAll(temp);
}
}
return result;
}
public void quickSort(int[] nums, int left, int right){
if(left>=right) return;
int tempVal = nums[left];
int i =left, j=right;
while(i<j){
while(j>i && tempVal<=nums[j])j--;
if(i<j){
nums[i++] = nums[j];
}
while(j>i && tempVal>=nums[i])i++;
if(i<j){
nums[j--] = nums[i];
}
// System.out.printf("%d %d\n", i, j);
}
nums[i] = tempVal;
quickSort(nums, left, i-1);
quickSort(nums, i+1, right);
}
public List<List<Integer>> towSum(int[] nums, int targetIndex){
List<List<Integer>> group = new ArrayList<>();
int i = targetIndex +1, j=nums.length-1;
int target = -1 * nums[targetIndex];
while(i<j){
if(nums[i] + nums[j] == target){
List<Integer> temp = new ArrayList<Integer>();
temp.add(nums[targetIndex]);
temp.add(nums[i]);
temp.add(nums[j]);
group.add(temp);
while(j>i && nums[j-1] == nums[j])j--;
while(j>i && nums[i+1] == nums[i])i++;
i++;
j--;
}else if(nums[i] + nums[j]<target){
i++;
}else{
j--;
}
}
return group;
}
}