Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
note:先将数组排序,复杂度为Log(n),从两边往中间找,复杂度为Log(),在找的过程中要注意去重,分别有两次去重,第一次在进入循环找数之前,第二次在找到数之后,begin右移,end左移,再次比较begin和end的数是否与前一步的数值相等,如若相等,则再次移动
public static List<List<Integer>> threeSum(int[] nums) {
/**
* 优化过后的算法
*/
List<List<Integer>> ret = new ArrayList<>();
if (nums == null || nums.length < 3) return ret;
int len = nums.length;
Arrays.sort(nums);
for (int i = 0; i < len; i++) {
// 减少无意义的循环
if (nums[i] > 0) break;
// 避免重复
if (i > 0 && nums[i] == nums[i - 1]) continue;
int begin = i + 1;
int end = len - 1;
while (begin < end) {
int sum = nums[i] + nums[begin] + nums[end];
if (sum == 0) {
List<Integer> list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[begin]);
list.add(nums[end]);
ret.add(list);
begin++;
end--;
// 避免重复
while (begin < end && nums[begin] == nums[begin - 1])
begin++;
while (begin < end && nums[end] == nums[end + 1])
end--;
} else if (sum > 0)
end--;
else
begin++;
}
}
return ret;
}