Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
-----
先對數組進行排序,固定一個標點,設置兩個指針,左指針和右指針,分別從標點之後的位置和數組的最後一個位置開始計算。
排序的好處就是可以避免數值重複。
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
for (int i =0;i<nums.length-2;i++) {
if (i > 0 && nums[i] == nums[i-1]) continue;
left = i +1;
right = nums.length - 1;
while (left < right) {
if(nums[i]+nums[left]+nums[right]==0){
list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[left]);
list.add(nums[right]);
lists.add(list);
while(left<right&&nums[left]==nums[left+1]) left++; //如果遇到下一個數值相等就往右移動
while(left<right&&nums[right]==nums[right-1]) right--; //如果遇到下一個數值相等就往左移動
left++;
right--;
}else if(nums[i]+nums[left]+nums[right]<0){
left++;
}else{
right--;
}
}
}
return lists;
}