Skip to content

Commit ebc8eaf

Browse files
MEDIUM/src/medium/_3SumClosest.java
1 parent 0f3d16c commit ebc8eaf

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

MEDIUM/src/medium/_3SumClosest.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)