LC.P16[最接近的三数之和]

方法一:排序+双指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length, ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < n - 2; ++i) {
int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return sum;
if (Math.abs(sum - target) < Math.abs(ans - target)) ans = sum;
if (sum < target) ++j;
else if (sum > target) --k;
}
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(logn)$

方法二:优化

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
36
37
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length, ans = nums[0] + nums[1] + nums[2];
for (int i = 0; i < n - 2; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;

int t = nums[i] + nums[i + 1] + nums[i + 2];
if (t > target) {
// 无论后面怎么选,选出的三个数的和不会比当前小
if (t - target < Math.abs(ans - target)) {
ans = t;
}
break;
}

t = nums[i] + nums[n - 2] + nums[n - 1];
if (t < target) {
// 由于已经排序,当前和仍小于target,则无法找到比当前更优的答案,跳过后续步骤
if (target - t < Math.abs(ans - target)) {
ans = t;
}
continue;
}

int j = i + 1, k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum == target) return sum;
if (Math.abs(sum - target) < Math.abs(ans - target)) ans = sum;
if (sum < target) ++j;
else --k;
}
}
return ans;
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(logn)$