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:
- Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
- The solution set must not contain duplicate triplets.
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);//sort进行排序
List<List<Integer>> list = new ArrayList<List<Integer>>();
for(int i = 0; i < nums.length-2; i++) {
if(i > 0 && (nums[i] == nums[i-1]))
continue;//避免重复
for(int j = i+1, k = nums.length-1; j < k;) {
int sum = nums[i] + nums[j] + nums[k];
if(sum == 0) {
list.add(Arrays.asList(nums[i],nums[j],nums[k]));
j++;k--;
while((j < k) && (nums[j] == nums[j-1]))
j++;//避免重复
while((j < k) && (nums[k] == nums[k+1]))
k--;//避免重复
}else if (sum > 0)
k--;//结果大于0,大数往里缩
else
j++;//结果小于0,小数往里缩
}
}
return list;
}
}
//大致思路就是先排序,然后第一个数从0到num.length-2遍历,后面俩数初始放在最前面和最后面,然后慢慢的向里面靠近。此算法打败了92.68%的人。
//发现很多算法题都是两边入手往里,或者找到中间值向外扩。