题目描述:
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
解答代码:
public class Unit15 {public static List<List<Integer>> threeSum(int[] nums) {Arrays.sort(nums);List<List<Integer>> result = new ArrayList<List<Integer>>();for (int i = 0; i < nums.length; i++) {// 右边全部大于0,没有判断的意义。if (nums[i] > 0) {break;}// 结果与上一次循环重复if (i > 0 && 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 += 1;while (left < right && nums[left] == nums[left - 1]) {left += 1;}} else if (sum > 0) {right -= 1;while (left < right && nums[right] == nums[right + 1] ) {right -= 1;}} else {result.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));left += 1;right -= 1;while (left < right && nums[left] == nums[left - 1]) {left += 1;}while (left < right && nums[right] == nums[right + 1] ) {right -= 1;}}}}return result;}public static void main(String[] args) {int[] nums = new int[] {-2,0,1,1,2};// int[] nums = new int[] {-1, 0, 1, 2, -1, -4};List<List<Integer>> result = threeSum(nums);for (List<Integer> list : result) {System.out.println(list.toString());}}}
解答思路:
1.排序(必须排序,不然没得执行)
2.遍历
3.从第一个节点开始,左边第一个(当前节点的右边第一个)是左节点,最后一个节点是右节点。
左右节点相加与当前节点和为0,则追加到集合中。
4.判断的过程中,sum < 0,左节点移动到下一位(右移)。sum > 0,右节点移动到下一位(左移)。
