Skip to content

Commit 89924f4

Browse files
authored
Create 16. 3Sum Closest
1 parent 81603c3 commit 89924f4

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

16. 3Sum Closest

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
public class Solution {
2+
public int threeSumClosest(int[] nums, int target) {
3+
if(nums.length< 3 || nums == null ){
4+
return -1;
5+
}
6+
Arrays.sort(nums);
7+
int ans = nums[0] + nums[1] + nums[2];
8+
for(int i = 0; i< nums.length-2 ; i++){
9+
int left = i+1;
10+
int right = nums.length-1;
11+
while(left< right){
12+
int sum = nums[i] + nums[left] + nums[right];
13+
if(Math.abs(target-sum) < Math.abs(target - ans)){
14+
ans = sum;
15+
}
16+
if(target <= sum){
17+
right--;
18+
}else{
19+
left++;
20+
}
21+
}
22+
}
23+
24+
return ans;
25+
}
26+
}

0 commit comments

Comments
 (0)