File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ import java .util .Arrays ;
4
+
5
+ public class _3SumClosest {
6
+ /**One implicit requirement is that you must have THREE elements!!! You cannot have just one!*/
7
+
8
+ /**Another cool trick that I learned here is that:
9
+ * after comparing the absolute difference, we'll see if thisSum > target or not, then we decide to shift left or right pointer.*/
10
+
11
+
12
+ public int threeSumClosest (int [] nums , int target ) {
13
+ if (nums == null || nums .length == 0 ) return 0 ;
14
+ Arrays .sort (nums );
15
+ int len = nums .length ;
16
+ if (len < 3 ){
17
+ int sum = 0 ;
18
+ for (int i : nums ){
19
+ sum += i ;
20
+ }
21
+ return sum ;
22
+ }
23
+ int sum = nums [0 ] + nums [1 ] + nums [2 ];
24
+ for (int i = 0 ; i < nums .length -2 ; i ++){
25
+ int left = i +1 , right = nums .length -1 ;
26
+ while (left < right ){
27
+ int thisSum = nums [i ] + nums [left ] + nums [right ];
28
+ if (Math .abs (target - thisSum ) < Math .abs (target - sum )) {
29
+ sum = thisSum ;
30
+ if (sum == target ) return sum ;
31
+ }
32
+ else if (target > thisSum ){
33
+ left ++;
34
+ } else {
35
+ right --;
36
+ }
37
+ }
38
+ }
39
+ return sum ;
40
+ }
41
+
42
+ }
You can’t perform that action at this time.
0 commit comments