File tree Expand file tree Collapse file tree 1 file changed +33
-1
lines changed
src/main/java/com/fibers/algorithm/leetcode/_016 Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change 1
1
package com .fibers .algorithm .leetcode ._016 ;
2
+
3
+ import java .util .Arrays ;
4
+
2
5
public class Solution {
6
+ public int threeSumClosest (int [] nums , int target ) {
7
+ if (nums == null || nums .length < 3 ) {
8
+ return 0 ;
9
+ }
10
+
11
+ Arrays .sort (nums );
12
+ int result = nums [0 ] + nums [1 ] + nums [2 ];
13
+
14
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
15
+ int start = i + 1 ;
16
+ int end = nums .length - 1 ;
17
+ while (start < end ) {
18
+ int sum = nums [i ] + nums [start ] + nums [end ];
19
+
20
+ if (Math .abs (sum - target ) < Math .abs (result - target )) {
21
+ result = sum ;
22
+ }
23
+
24
+ if (sum > targ
7945
et ) {
25
+ end --;
26
+ } else if (sum < target ) {
27
+ start ++;
28
+ } else {
29
+ return sum ;
30
+ }
31
+ }
32
+ }
33
+ return result ;
34
+ }
3
35
}
4
-
36
+
You can’t perform that action at this time.
0 commit comments