-
Notifications
You must be signed in to change notification settings - Fork 15
/
3-sum-closest.java
41 lines (35 loc) · 1.01 KB
/
3-sum-closest.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
34
35
36
37
38
39
40
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
/**
* @param numbers: Give an array numbers of n integer
* @param target : An integer
* @return : return the sum of the three integers, the sum closest target.
*/
public int threeSumClosest(int[] numbers ,int target) {
// write your code here
Arrays.sort(numbers);
int sum = 0;
int err = Integer.MAX_VALUE;
for (int i = 0; i < numbers.length; i++) {
int left = i + 1;
int right = numbers.length - 1;
while (left < right) {
int tempSum = numbers[i] + numbers[left] + numbers[right];
int tempErr = Math.abs(target - tempSum);
if (tempErr == 0) {
return tempSum;
} else if (tempErr < err) {
err = tempErr;
sum = tempSum;
}
if (tempSum > target) {
right--;
} else {
left++;
}
}
}
return sum;
}
}