- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathSolution16.java
More file actions
Latest commit
executable file
·52 lines (43 loc) · 1.28 KB
/
Copy pathSolution16.java
File metadata and controls
executable file
·52 lines (43 loc) · 1.28 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
47
48
49
50
51
52
importjava.lang.reflect.Array;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.Collections;
importjava.util.List;
/**
* Created by slade on 2019/6/5.
*/
publicclassSolution16 {
publicintthreeSumClosest(int[] nums, inttarget) {
Arrays.sort(nums);
intlength = nums.length;
intres = nums[0] + nums[1] + nums[length - 1];
for (inti = 0; i < length - 2; i++) {
intfirst = i + 1;
intlast = length - 1;
if (i != 0 && nums[i - 1] == nums[i]) {
continue;
}
while (first < last) {
intcur = nums[first] + nums[last] + nums[i];
if (target == cur) {
returntarget;
}
if (Math.abs(target - cur) < Math.abs(target - res)) {
res = cur;
}
if ((target - cur) > 0) {
first++;
}
if ((target - cur) < 0) {
last--;
}
}
}
returnres;
}
publicstaticvoidmain(String[] args) {
int[] a = {0, 2, 1, -3};
Solution16s = newSolution16();
System.out.println(s.threeSumClosest(a, 1));
}
}