leetcode第15题
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[ [-1, 0, 1], [-1, -1, 2] ]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 采用滑动窗口,时间复杂度为:O(n log(n))
* 例如, 给定数组 nums = [-1, 0, 1, 5, -1, -4]
*满足要求的三元组集合为:
*[[-4, -1, 5],[-1, 0, 1]]
*/
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 3) {
return list;
}
// 先排序,同时避免求重复解
Arrays.sort(nums);
//[-4, -1, -1, 0, 1, 5]
//因为每三个一组,所以至少是倒数第三个开始算。又因为要等于零,三个数最左边的数只能是小于等于0
for (int i = 0; i < nums.length - 2 && nums[i] <= 0;) {
int l = i + 1; //左指针
int r = nums.length - 1; //右指针
while (l < r) {
int sum = nums[i] + nums[l] + nums[r];
if (sum == 0) {
//先存nums[i],nums[l],nums[r]进去list,再l++,r--进入下一次判断
list.add(Arrays.asList(nums[i], nums[l++], nums[r--]));
//相同就继续++,防止重复取数
while (l < r && nums[l] == nums[l - 1]) { //这里不用if的原因就是万一真的有连续重复的几个数。。。
l++;
}
//相同就继续--,防止重复取数
while (r > l && nums[r] == nums[r + 1]) {
r--;
}
} else if (sum < 0) { //小于0就代表左指针要往右滑动取大点的数
l++;
} else { //大于0就代表右指针要往左滑动取小点的数
r--;
}
}
//走完一轮循环,i++进入下一轮
i++;
//相同就++,防止重复取数
while (i < nums.length - 2 && nums[i] == nums[i - 1]) {
i++;
}
}
return list;
}
public static void main(String[] args) {
int[] nums = new int[]{-1, 0, 1, 5, -1, -4};
Solution solution = new Solution();
List<List<Integer>> lists = solution.threeSum(nums);
for(List list : lists){
System.out.println(list);
}
}
}