Star

LeetCode 16. 3Sum Closest

Question

Given an array S of n integers, 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.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Explanation

固定一个值,然后用双指针遍历其他的值。找到绝对值之差最小的即可。

Code

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
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int diff = Integer.MAX_VALUE;
int result = 0;
if (nums == null || nums.length < 3) return -1;
Arrays.sort(nums);
for (int i=0; i<nums.length; i++) {
int start = i+1;
int end = nums.length - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (Math.abs(target - sum) < diff) {
diff = Math.abs(target - sum);
result = sum;
}
if (sum < target) {
start ++;
} else{
end --;
}
return result;
}
}