/*
15.给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
*/
//方法一,个人解法正确,但是效率太低,时间复杂度O(N ^ 3),时间超时,无法提交至LeetCode
public static List<List<Integer>> threeSum(int[] nums) {
//int[] nums = {3,0,-2,-1,1,2,6,4,-3,8,-5,-9};
//Arrays.sort(nums);
List<Integer> integers = null;
List<List<Integer>> res = new LinkedList<List<Integer>>();
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (k < nums.length - 1 && nums[k] == nums[k + 1]) {
k++;
continue;
}
if (nums[i] + nums[j] + nums[k] == 0) {
integers = Arrays.asList( nums[i], nums[j], nums[k] );
Collections.sort( integers );
if (!res.contains( integers )) res.add( integers );
break;
}
}
}
}
return res;
}
//方法二,来源于LeetCode Discuss,很棒的解法,时间复杂度O(N ^ 2)
public List<List<Integer>> threeSum2(int[] num) {
Arrays.sort( num );
List<List<Integer>> res = new LinkedList<>();
int numLastIndex = num.length - 1;
for (int i = 0; i < numLastIndex - 1; i++) {
if (i == 0 || isCurrentDifferentFromPrevious( num, i )) {
int lo = i + 1;
int hi = numLastIndex;
int sum = 0 - num[i]; // a + b = 0 - c
while (lo < hi) {
if (num[lo] + num[hi] == sum) {
// found
res.add( Arrays.asList( num[i], num[lo], num[hi] ) );
while (lo < hi && num[lo] == num[lo + 1]) lo++; // dups on low index, move L index++
while (lo < hi && num[hi] == num[hi - 1]) hi--; // dups on high index, move H index--
// move indices to new positions with different values
lo++;
hi--;
} else if (num[lo] + num[hi] < sum) {
lo++; // sum too small
} else {
hi--; // sum too large
}
}
}
}
return res;
}
private boolean isCurrentDifferentFromPrevious(int[] num, int i) {
return i > 0 && num[i] != num[i - 1];
}