描述
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解析
先排序,再确定一个数字,用后面的数据获取0 - num[i]的值,转成 2sum的问题。要注意跳过重复数据。
代码
解法1(解析所述)
public static List<List<Integer>> threeSum3(int[] num) { if (num == null || num.length < 3) { return new ArrayList<>(); } Arrays.sort(num); List<List<Integer>> res = new ArrayList<>(); for (int i = 0; i < num.length - 2; i++) { if (i == 0 || (i > 0 && num[i] != num[i - 1])) { int target = 0 - num[i]; int start = i + 1; int end = num.length - 1; while (start < end) { if (num[start] + num[end] == target) { res.add(Arrays.asList(num[i], num[start], num[end]));
//去除重复元素 while (start < end && num[start] == num[start + 1]) { start++; } while (start < end && num[end] == num[end - 1]) { end--; } start++; end--; } else if (num[start] + num[end] > target) { end--; } else { start++; } } } } return res; }
数组中找等于指定数的集合
也可以用数组num,在其中找n个数等于指定数的解法。