原题:
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] ]复杂度O(n*n*logn) ,代码太丑,觉得方法有问题,不想讲代码思路了,各种检查一定是方法不好。
这题还有复杂度更低的解法
public class Solution {
class Num_compare implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1 - o2;
}
}
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
int idx1, idx2, left, right, mid;
int sum,last;
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(idx1 = 0; idx1 < nums.length - 2; ++idx1){
while(idx1 < nums.length - 3 && nums[idx1] == nums[idx1+1] && nums[idx1] != 0){
if(nums[idx1] != nums[idx1+2]){
break;
}
++idx1;
}
while(idx1 < nums.length - 3 && nums[idx1] == 0 && nums[idx1] == nums[idx1+1] && nums[idx1] == nums[idx1+2] && nums[idx1] == nums[idx1+3]){
++idx1;
}
System.out.print("idx1 ");
System.out.println(idx1);
for(idx2 = idx1 + 1; idx2 < nums.length - 1 && nums[idx1] + nums[idx2] <= 0; ++idx2){
if(idx1 < nums.length - 3 && nums[idx1] == nums[idx1+1] && nums[idx1] != nums[idx2]){
++idx1;
}
while(idx2 < nums.length-2 && nums[idx2] == nums[idx2+1]){
if(nums[idx2] != nums[idx2+2] && nums[idx1]+nums[idx2]+nums[idx2+1] == 0){
break;
}
++idx2;
}
left = idx2+1;
right = nums.length - 1;
while(left>=0 && right < nums.length && left <= right){
mid = (left + right)/2;
sum = nums[idx1] + nums[idx2] + nums[mid];
if(sum == 0){
List<Integer> res = new ArrayList<Integer>();
res.add(nums[idx1]);
res.add(nums[idx2]);
res.add(nums[mid]);
last = nums[mid];
result.add(res);
break;
}
else if (sum > 0){
right = mid - 1;
}
else if (sum < 0){
left = mid + 1;
}
}
}
}
return result;
}
}