For example: given array S = {-1 0 1 2 -1 -4},
A solution set is:
(-1, 0, 1)
(-1, -1, 2)
思路:
使用指针(Two Pointers) 先将给出的数组按照进行排序 然后依次遍历后面的数令后面的两个数之和等于前面的数(因为需要找出三个数之和为0的三个数) 即可;
代码1:
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new Linkedlist<List<Integer>>(); //要注意此处第一:List是接口,需要实现类ArrayList或者LinkedList,不能new List;第二:int是基本数据类型,只能用Integer***(切记切记)***
Arrays.sort(nums); //先进行排序
for(int i = 0;i < nums.length-2;i++){
if (i == 0 || (i > 0 && nums[i]!=nums[i-1])){
int j = i+1,k = nums.length-1,sum = 0 - nums[i];
while(j < k){
if(nums[j] + nums[k] == sum){
list.add(Arrays.asList(nums[i],nums[j],nums[k]));
while(j < k && nums[j] == nums[j+1]) j++;
while(j < k && nums[k] == nums[k-1]) k--;
j++;
k--; //不满足上述while则也要进行j++ k--别忘了
}else if(nums[j] + nums[k] < sum) j++; //如果后面两个数之和小于前面的数的 则进行j++
else k--; //相反则进行k--
}
}
}
return list;
}
}
代码2:
public List<List<Integer>> threeSum(int[] A) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(A.length == 0 || A == null)
return res;
Arrays.sort(A);
for(int i = 0 ; i < A.length ; i++){
if(i-1 >= 0 && A(i) == A(i-1)) continue; //continue是跳出本次循环接着进行下次、而break全部跳出
int left = i + 1,right = A.length - 1,sum = 0;
while (left < right) { // 下面Two Pointers
sum = A(i) + A(left) + A(right);
if(sum = 0){
res.add(Array.asList(A(i),A(left),A(right)));
while (left + 1 < right && A[left] == A[left+1])// Ignore same numbers
left++;
while (right -1 > left && A[right] == A[right-1])// Ignore same numbers
right--;
left++;
right--;
}
else if (sum < 0) {
left++;
} else {
right--;
}
}
}
return res;
}