16 3Sum Closest

1. Question

Given an arraySofnintegers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
1
For example, given array S = {-1 2 1 -4}, and target = 1.
2
3
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Copied!

2. Implementation

(1) Two Pointers
1
class Solution {
2
public int threeSumClosest(int[] nums, int target) {
3
if (nums.length < 3) {
4
return Integer.MAX_VALUE;
5
}
6
7
Arrays.sort(nums);
8
int res = nums[0] + nums[1] + nums[2];
9
10
for (int i = 0; i < nums.length - 2; i++) {
11
int j = i + 1, k = nums.length - 1;
12
13
while (j < k) {
14
int sum = nums[i] + nums[j] + nums[k];
15
16
if (sum == target) {
17
res = sum;
18
break;
19
}
20
else if (Math.abs(sum - target) < Math.abs(res - target)) {
21
res = sum;
22
}
23
24
if (sum > target) {
25
--k;
26
}
27
else {
28
++j;
29
}
30
}
31
}
32
return res;
33
}
34
}
Copied!

3. Time & Space Complexity

Two Pointers: 时间复杂度O(n^2), 空间复杂度O(logn),sorting需要logn的空间
Last modified 2yr ago