-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum Closest 3
31 lines (25 loc) · 924 Bytes
/
3Sum Closest 3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int minimum=Integer.MAX_VALUE;
int sum=0, left, right;
for (int i=0; i<nums.length-2; i++) {
left=i+1;
right=nums.length-1;
while (left<right) {
if (Math.abs(nums[i]+nums[left]+nums[right]-target)<minimum)
{minimum=Math.abs(nums[i]+nums[left]+nums[right]-target);
sum=nums[i]+nums[left]+nums[right];
}
if ((nums[i]+nums[left]+nums[right])<target) {
left++;
}
else if ((nums[i]+nums[left]+nums[right])>target) {
right--;
}
else return target;
}
}
return sum;
}
}