/*
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
/*
思路: 首先想到的肯定是穷举,时间复杂度为O(n^3) , 但如果使用这种方法,也实在称不上算法题了,果不其然,超时.
[-1, 0, 1, 2, -1, -4] 对于这个数组,可以先固定一个数,然后判断其他2个数的和是否与这个数相反,如果
相反,自然就是一个解.
****先排序****
首先固定一个数,这个题中,从下标i=0开始,一直到length - 3.(因为固定的这个数右面起码有2个位置留给另外2个数用于求和的.)
另外两个数分别从 pos = i+1,和pos = length - 1 开始,向中间遍历,求和sum,分析和.
1.如果sum与固定的数刚好相反,加入到解中。但也要考虑到去重的问题:如果这个数和接下来的数相同,就跳过
2.如果sum大于固定的数,就让sum变小 , right++
3.如果sum小于固定的数,就让sum变大 , left++
时间复杂度为O(n^2)
*/
1 class Solution15 {
2
3 public List<List<Integer>> threeSum(int[] nums) {
4 List<List<Integer>> res = new ArrayList<>();
5 if (nums == null || nums.length < 3) {
6 return res;
7 }
8 Arrays.sort(nums);
9 for (int i = 0; i < nums.length - 2; i++) {
10 if (i > 0 && nums[i] == nums[i - 1]) { //剪枝,如果这一步不进行剪枝,会产生重复解
11 continue;
12 }
13 if (nums[i] > 0) {
14 break;
15 }
16 int left = i + 1;
17 int right = nums.length - 1;
18 while (left < right) {
19 int sum = nums[left] + nums[right];
20 if (sum + nums[i] == 0) { //加入到解中,并剪枝(while),如果这一步不进行剪枝,会产生重复解
21 res.add(Arrays.asList(nums[i], nums[left], nums[right]));
22 while (left < right && nums[left] == nums[left + 1]) {
23 ++left;
24 }
25 while (right > left && nums[right] == nums[right - 1]) {
26 --right;
27 }
28 ++left;
29 --right;
30 } else if (sum + nums[i] < 0) { //如果和小于0,让和变大一些
31 ++left;
32 } else { //如果和大于0,让和变小一些
33 --right;
34 }
35 }
36 }
37 return res;
38 }
39 }