鲁迅说过,不经一番寒彻骨,怎得梅花扑鼻香。两数之和都搞定了,三数之和也不在话下,今天就让我们继续来刷《二哥的 LeetCode 刷题笔记》。
题意
给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]]
满足 i != j、i != k 且 j != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0
。请你返回所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
难度
中等
示例
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1] 和 [-1,-1,2] 。
注意,输出的顺序和三元组的顺序并不重要。
输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。
输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。
分析 1
三数之和,很容易就让我们想到两数之和,都是在数组中找出满足某种条件的元素。但是这道题比两数之和要复杂一些,增加了一个数嘛。
如果想套用两数之和的思路,我们可以先固定一个数,然后再去找另外两个数,这样就可以转换为两数之和的问题了。
下面是两数之和的题解:
class Solution {
// 定义一个方法 twoSum,接收一个整数数组 nums 和一个目标值 target
public int[] twoSum(int[] nums, int target) {
// 创建一个哈希表来存储数组元素和它们的索引
Map<Integer, Integer> map = new HashMap<>();
// 遍历数组中的每个元素
for(int i = 0; i < nums.length; i++){
// 计算与当前元素相配对的另一个元素的值
int complement = target - nums[i];
// 检查哈希表中是否已存在这个配对元素
if(map.containsKey(complement))
// 如果存在,返回当前元素的索引和配对元素的索引
return new int[]{i, map.get(complement)};
// 将当前元素及其索引添加到哈希表中
map.put(nums[i], i);
}
// 如果遍历完数组都没有找到符合条件的两个数,则抛出异常
throw new IllegalArgumentException("没找到");
}
}
我们借助这个题解,来完成三数之和的题解:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
// 遍历数组中的每个元素
for (int i = 0; i < nums.length - 1; i++) {
// 创建一个集合存储已经遍历过的数字,避免重复使用
Map<Integer, Integer> map = new HashMap<>();
for (int j = i + 1; j < nums.length; j++) {
int complement = -nums[i] - nums[j];
// 如果 complement 在集合中,说明找到了一组解
if (map.containsKey(complement)) {
// 将结果添加到集合中,这里使用数组并排序是为了避免重复
Integer[] temp = new Integer[]{nums[i], nums[j], complement};
Arrays.sort(temp);
res.add(Arrays.asList(temp));
}
// 将当前数字添加到集合中
map.put(nums[j], j);
}
}
return new ArrayList<>(res);
}
}
思路如下:
①、第一层 for 循环,将 nums[i]
作为第一个数,然后再去找另外两个数。
②、第二层 for 循环,将 nums[j]
作为第二个数,然后再去找第三个数 int complement = -nums[i] - nums[j]
。因为 nums[i] + nums[j] + nums[k] == 0
,所以 nums[k] == -nums[i] - nums[j]
。
③、如果 complement
在 Map 中,说明找到了一组解,将结果添加到 HashSet 中,这里使用数组并排序是为了避免重复。
假如我们把排序去掉 Arrays.sort(temp);
,就会出现这样的错误:
因为 [0,-1,1],[-1,1,0]
本来算是一种结果 [-1,0,1]
,不排序的话,就算是两种结果,都会放入 HashSet。
之所以用 HashSet,就是因为 HashSet 会自动去重,第二次 add [-1,0,1]
回覆盖第一次 add。这个我在《二哥的 Java 进阶之路》里有详细讲过。
好,当输入是 [-1,0,1,2,-1,-4]
时,我们来模拟一下整个题解过程。
①、第一层 for 循环,将 nums[i]
作为第一个数,此时 nums[i] = -1
,然后再去找另外两个数。
②、第二层 for 循环,将 nums[j]
作为第二个数,此时 nums[j] = 0
,然后再去找第三个数 int complement = -nums[i] - nums[j] = 1
。
把 nums[j] = 0
put 到 Map 中,此时 Map 的键中有 [0]
。
继
回复