面试经典-三数之和

题目

15. 三数之和

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != kj != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

1
2
3
4
5
6
7
8
输入: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] 。
注意,输出的顺序和三元组的顺序并不重要。

示例 2:

1
2
3
输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0

示例 3:

1
2
3
输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0

提示:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

题解

方法一(暴力法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public static List<List<Integer>> threeSum(int[] nums) {
int target = 0;
if (nums.length < 3) {
return new ArrayList<>();
}
List<Integer> list = Arrays.stream(nums).boxed().sorted().distinct().toList();
if (list.size() == 1 && list.get(0) == target) {
return List.of(Arrays.asList(0, 0, 0));
}
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int size = nums.length - 1; size > 0; size--) {
int left = 0;
int right = size - 1;
int current = nums[size];
while (left < right) {
int sum = current + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[left], nums[right], current));
right--;
}
if (sum < target) {
left++;
}
if (sum > target) {
right--;
}
}
}
return result.stream().distinct().toList();
}

会超时😭😭😭

image-20241119155648931

方法二(优化上面解法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public List<List<Integer>> threeSum(int[] nums) {
int target = 0;
if (nums.length < 3 || nums.length > 30000) {
return new ArrayList<>();
}
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
// int[] nums = {0,0,0,0,0};
for (int i = 0, len = nums.length; i < len; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = len - 1;
while (left < right) {
int sum = nums[right] + nums[left] + nums[i];
if (sum == 0) {
list.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
right--;
} else if (sum > 0){
right--;
} else {
left++;
}
}
}
return list;
}

nice😀😀😀😀

image-20241119160520584