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%的人。
//发现很多算法题都是两边入手往里,或者找到中间值向外扩。
本文介绍了一种解决三数之和问题的有效算法。通过首先对数组进行排序,然后使用双指针技巧来寻找所有唯一三元组,使得这三个数相加等于零。该算法巧妙地避免了重复解,并且效率高。
1570

被折叠的 条评论
为什么被折叠?



