- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem16.java
More file actions
Latest commit
46 lines (42 loc) · 1.2 KB
/
Copy pathProblem16.java
File metadata and controls
46 lines (42 loc) · 1.2 KB
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
importjava.util.*;
classProblem16 {
publicstaticvoidmain(String[] args) {
int[] nums = newint[]{0, 1, 2};
inttarget = 3;
System.out.println(newProblem16().threeSumClosest(nums, target));
}
publicintthreeSumClosest(int[] nums, inttarget) {
intres = Integer.MAX_VALUE;
ints = 0;
List<Integer> numsList = newArrayList<>();
for(inti = 0; i < nums.length; i++) {
numsList.add(nums[i]);
}
Collections.sort(numsList);
for (inti = 0; i < nums.length-1; i++) {
intsum = target - numsList.get(i);
intk = nums.length - 1;
intj = i + 1;
while ( j < k) {
inttmp = numsList.get(j) + numsList.get(k);
if (tmp == sum) {
return0;
}
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);
}
}
}
}
returns;
}
}