-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem16.java
46 lines (42 loc) · 1.2 KB
/
Problem16.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
41
42
43
44
45
46
import java.util.*;
class Problem16 {
public static void main(String[] args) {
int[] nums = new int[]{0, 1, 2};
int target = 3;
System.out.println(new Problem16().threeSumClosest(nums, target));
}
public int threeSumClosest(int[] nums, int target) {
int res = Integer.MAX_VALUE;
int s = 0;
List<Integer> numsList = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
numsList.add(nums[i]);
}
Collections.sort(numsList);
for (int i = 0; i < nums.length-1; i++) {
int sum = target - numsList.get(i);
int k = nums.length - 1;
int j = i + 1;
while ( j < k) {
int tmp = numsList.get(j) + numsList.get(k);
if (tmp == sum) {
return 0;
}
if(tmp < sum) {
j++;
if (res > (sum-tmp)) {
res = sum-tmp;
s = tmp + numsList.get(i);
}
} else {
k--;
if (res > (tmp-sum)) {
res = tmp-sum;
s = tmp + numsList.get(i);
}
}
}
}
return s;
}
}