We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 81603c3 commit 89924f4Copy full SHA for 89924f4
16. 3Sum Closest
@@ -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