File tree 1 file changed +37
-11
lines changed
solution/0000-0099/0016.3Sum Closest
1 file changed +37
-11
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int threeSumClosest (int [] nums , int target ) {
3
- int result = nums [0 ]+nums [1 ]+nums [2 ];
4
3
Arrays .sort (nums );
5
- for (int i = 0 ;i <nums .length -2 ;i ++){
6
- int start = i +1 ,end =nums .length -1 ;
7
- while (start <end ){
8
- int cache = nums [i ]+nums [start ]+nums [end ];
9
- if (Math .abs (cache -target )<Math .abs (result -target )) result = cache ;
10
- if (cache < target ) start ++;
11
- else if (cache > target ) end --;
12
- else return result ;
4
+ int bestAns = 100000 ;
5
+ for (int i = 0 ;i + 2 < nums .length ;i ++) {
6
+ if (i != 0 && nums [i ] == nums [i - 1 ]) {
7
+ continue ;
8
+ }
9
+ int j = i + 1 , k = nums .length - 1 ;
10
+ while (j < k ) {
11
+ int sum = nums [i ] + nums [j ] + nums [k ];
12
+ if (sum == target ) {
13
+ return sum ;
14
+ }
15
+ if (Math .abs (target - bestAns ) > Math .abs (target - sum )) {
16
+ bestAns = sum ;
17
+ }
18
+ if (sum > target ) {
19
+ int k0 = k - 1 ;
20
+ while (j < k0 && nums [k ] == nums [k0 ]) {
21
+ k0 --;
22
+ }
23
+ if (j == k0 ) {
24
+ break ;
25
+ } else {
26
+ k = k0 ;
27
+ }
28
+ } else {
29
+ int j0 = j + 1 ;
30
+ while (j0 < j && nums [j ] == nums [j0 ]) {
31
+ j0 ++;
32
+ }
33
+ if (j0 == k ) {
34
+ break ;
35
+ } else {
36
+ j = j0 ;
37
+ }
38
+ }
13
39
}
14
40
}
15
- return result ;
41
+ return bestAns ;
16
42
}
17
- }
43
+ }
You can’t perform that action at this time.
0 commit comments