可以发现,我们最能想到的办法是n*n*log(n),但有没有办法n*n的办法解决呢,答案是有的:
首先我们肯定得枚举一次List,那么还剩下O(n)的复杂度,可以想到我们枚举的List,a + b + c = 0
a + b = -c 就当枚举的-c ,我们需要去List里找 a + b,由于List里的数的递增性,我们可以尺取的取出 a + b
另左端点在0,右端点在List.length - 1,List[0] + List[List.length - 1] 如果比 -c 大,那就让 右端点向左靠,这样
会当 a + b 减小,反之比 -c 小,那么左端点自然向右移。
class Solution {
static List<List<Integer>> ret = new ArrayList<List<Integer>>();
public static List<List<Integer>> threeSum(int[] nums) {
ret.clear();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
int x = nums[i];
twoSum(nums, i + 1, -x);
while(i < nums.length - 2 && nums[i] == nums[i + 1]) i++;
}
return ret;
}
public static void twoSum(int[] nums, int start, int value) {
int l = start;
int r = nums.length-1;
while(l < r) {
if(nums[l] + nums[r] == value) {
List<Integer> list = new ArrayList<Integer>();
list.add(nums[start - 1]);
list.add(nums[l]);
list.add(nums[r]);
ret.add(list);
while(l < r && nums[l + 1] == nums[l]) l++;
while(l < r && nums[r - 1] == nums[r]) r--;
l++; r--;
}
else if(nums[l] + nums[r] > value){
r--;
}
else l++;
}
}
}