15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
解题思想 :
- 要求不重复 首先想到寻找特殊值来确定 如最小值/最大值不同 则不同, 所以我们把数组排序
- 由于数组从小到大 所以我们确定一个最小值 然后用双指针来确定其他两个值
L = minIndex+1
R = length-1
- 为了结果不重复 我们在移动指针的时候还要考虑重复问题
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> returnList = new ArrayList<>();
if (nums.length < 3) {
return returnList;
}
Arrays.sort(nums);
int start = 0;
while (nums[start] <= 0 && start<= nums.length-3) {
int st = nums[start];
int r = nums.length - 1;
int l = start + 1;
while (l < r) {
int sum = nums[l] + nums[r] + st;
if (sum == 0) {
// 方式一: 手动新建ArrayList 省时间费空间
List<Integer> list = new ArrayList<>();
list.add(st);
list.add(nums[l]);
list.add(nums[r]);
returnList.add(list);
// 方式2: 调用Arrays工具类 省空间费时间
// returnList.add(Arrays.asList(st,nums[l],nums[r]));
while(l<r && nums[l] == nums[++l]);
while(l<r && nums[r] == nums[--r]);
}
if (sum <0) l++;
if (sum >0) r--;
}
while (start + 1 < nums.length && nums[start] == nums[++start]) ;
}
return returnList;
}