https://leetcode-cn.com/problems/3sum/
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解法:
package leetcode2;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* 2021/3/9 14:47
*
* @Author ayue
*/
public class Solution15 {
public List<List<Integer>> threeSum(int[] nums) {//排序加双指针
List<List<Integer>> res = new LinkedList<List<Integer>>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; ++i) {
if (i > 0) {
if (nums[i] == nums[i - 1]) {
continue;//去重
}
}
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left++;
while (left < right && nums[left] == nums[left - 1]) left++; // 去重
} else if (sum > 0) {
right--;
if (nums[right] < 0) {
break;
}
while (left < right && nums[right] == nums[right + 1]) right--; // 去重
} else {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
while (left < right && nums[right] == nums[right + 1]) right--; // 去重
while (left < right && nums[left] == nums[left - 1]) left++; // 去重
}
}
if (nums[i] > 0) {
break;
}
}
return res;
}
public static void main(String[] args) {
int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
Solution15 solution15 = new Solution15();
System.out.println(solution15.threeSum(nums).toString());
}
}