题目
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
- 来源:力扣(LeetCode)
- 链接:leetcode-cn.com/problems/3s…
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一
思路
前面做过1. 两数之和[简单]。那么这个就相当于对于每个nums[i],找它后面的两个数之和是-nums[i]就可以了。
注意:不能有重复的。可以考虑排个序。
代码
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
int n = nums.length;
Arrays.sort(nums);
for (int i = 0; i < n; i++) {
if (res.size() > 0 && res.get(res.size() - 1).get(0) == nums[i]) {
continue;
}
int target = -nums[i];
Map<Integer, Integer> map = new HashMap<>();
for (int j = i + 1; j < n; j++) {
if (map.containsKey(target - nums[j])) {
List<Integer> list = new LinkedList<>();
list.add(nums[i]);
list.add(target - nums[j]);
list.add(nums[j]);
if (res.size() > 0 && res.get(res.size() - 1).equals(list)) {
continue;
}
res.add(list);
}
map.put(nums[j], j);
}
}
return res;
}
解法二
思路
排序 + 双指针。
注意,上次的题目1. 两数之和[简单],是不能用 排序 + 双指针 的方式的,因为,“两数之和”要求返回的是下标。如果排序的话,下标就乱了。
本题返回的是数字。只要考虑不重复就可以了。
代码
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
Arrays.sort(nums);
int left = 0;
int right = 0;
for (int i = 0; i < nums.length - 1; i++) {
left = i + 1;
right = nums.length - 1;
while (left < right) {
if (nums[i] + nums[left] + nums[right] == 0) {
res.add(Arrays.asList(nums[i], nums[left], nums[right]));
left++;
right--;
} else if (nums[i] + nums[left] + nums[right] < 0) {
left++;
} else {
right--;
}
}
}
return new LinkedList<>(res);
}