File tree Expand file tree Collapse file tree 1 file changed +18
-23
lines changed Expand file tree Collapse file tree 1 file changed +18
-23
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int threeSumClosest (int [] nums , int target ) {
3
- int sum = Integer .MAX_VALUE ;
4
- Arrays .sort (nums );
5
-
6
- for (int i =0 ; i <nums .length ; i ++) {
7
- int j = i + 1 ;
8
- int k = nums .length - 1 ;
9
-
10
- while (j < k ) {
11
- int tempSum = nums [i ] + nums [j ] + nums [k ];
12
- if (sum == Integer .MAX_VALUE || Math .abs (sum - target ) > Math .abs (target - tempSum )) {
13
- sum = tempSum ;
14
- }
15
-
16
- if (tempSum > target ) {
17
- k --;
18
- }
19
- else {
20
- j ++;
21
- }
22
- }
2
+ public int threeSumClosest (int [] nums , int target ) {
3
+ Arrays .sort (nums );
4
+ int closestDiff = Integer .MAX_VALUE ;
5
+ for (int i = 0 ; i < nums .length ; i ++) {
6
+ int start = i + 1 ;
7
+ int end = nums .length - 1 ;
8
+ while (start < end ) {
9
+ int currSum = nums [i ] + nums [start ] + nums [end ];
10
+ if (Math .abs (target - currSum ) < Math .abs (closestDiff )) {
11
+ closestDiff = target - currSum ;
23
12
}
24
-
25
- return sum ;
13
+ if (currSum < target ) {
14
+ start ++;
15
+ } else {
16
+ end --;
17
+ }
18
+ }
26
19
}
20
+ return target - closestDiff ;
21
+ }
27
22
}
You can’t perform that action at this time.
0 commit comments