leetcode 16. 3sum closest

16. 3Sum Closest

Difficulty: Medium

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

1
2
3
Given array nums = [-1, 2, 1, -4], and target = 1.

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

Solution

Language: Java

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
class  {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return target;
}
Arrays.sort(nums);
int n = nums.length;
int min = Integer.MAX_VALUE;
int minSum = 0;
for (int i = 0; i < n - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = n - 1;
while (j < k) {
int res = nums[i] + nums[j] + nums[k];
if (Math.abs(res - target) < min) {
min = Math.abs(res - target);
minSum = res;
}
if (res == target) {
return res;
} else if (res > target) {
k--;
} else {
j++;
}
}
}
return minSum;
}
}