题目描述:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]例如, 给定数组 nums = [0, 0, 0, 0, -1, 0],
满足要求的三元组集合为:
[
[0, 0, 0]
]
解题思路:
一、暴力法:先排个序,去除重复的元素、暴力循环找出三数和相加等于0的数放进List,再去重数组,时间复杂度O(n^3)
二、巧妙:先排个序,去除重复的元素、模拟双指针,时间复杂度O(n^2)
代码:
一、暴力法:时间复杂度O(n^3) 。注:与通过的实例对比没错误,but 311 / 313 个通过测试用例(第311个用例没通过原因:超出时间限制)
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ls = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i - 1] == nums[i])
continue; // 去重
for (int j = i + 1; j < nums.length - 1; j++)
for (int k = j + 1; k < nums.length; k++)
if (nums[k] + nums[i] + nums[j] == 0)
ls.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
Set<List<Integer>> middleLinkedHashSet = new LinkedHashSet<>(ls);
List<List<Integer>> afterHashSetList = new ArrayList<>(middleLinkedHashSet);
return afterHashSetList;
}
二、排序+双指针:时间复杂度O(n^2)
public List<List<Integer>> threeSum2(int[] nums) {
Arrays.sort(nums); // 排序
List<List<Integer>> tuples = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i - 1] == nums[i]) continue; // 去重
int first = i + 1, last = nums.length - 1;
while (first < last) { // 因为如果只 first++ last 不变的话,即使得到了结果也是重复的
if (nums[last] > -nums[i] - nums[first]) {
while (first < last && nums[last - 1] == nums[last])
last--; // 右指针去重
last--;
} else if (nums[last] < -nums[i] - nums[first]) {
while (first < last && nums[first + 1] == nums[first])
first++; // 左指针去重
first++;
} else {
tuples.add(Arrays.asList(nums[i], nums[first], nums[last]));
while (first < last && nums[last - 1] == nums[last])
last--; // 左指针去重
while (first < last && nums[first + 1] == nums[first])
first++; // 右指针去重
last--;
first++;
}
}
}
return tuples;
}