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]
]
因爲本人比較菜,所以一開始想的當然是N3的遍歷,但是一個medium的題目肯定不能這麼簡單,所以這題就理解爲成a+b = -c的題目。然後可以用雙指針做,遍歷num[],0-num[i]作爲-c,left指針從i+1開始向右遍歷,right從右開始向左遍歷。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//先排序
Arrays.sort(nums);
//避免重複,將獲得的list先放入set中
Set<List> sets = new HashSet<>();
for(int i=0;i<nums.length;i++){
//如果num[i]>0就出現不了=0的情況所以break
if (nums[i]>0)break;
int target = 0-nums[i];
int j = i+1;int k = nums.length-1;//定義左右指針
while (j<k){
if (nums[j]+nums[k] == target){
List<Integer> set = new ArrayList<>();
set.add(nums[i]);set.add(nums[j]);set.add(nums[k]);
sets.add(set);
j++;k--;
}
//如果左右指針的數的sum小於target則從用更大的比較,所以j++,同理,如果小於target,則k--;
else if (nums[j]+nums[k]<target){
j++;
}
else {
k--;
}
}
}
List<List<Integer>> lists = new ArrayList<>();
for (List list: sets){
lists.add(list);
}
return lists;
}
}