-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path16. 3Sum Closest
30 lines (30 loc) · 996 Bytes
/
16. 3Sum Closest
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
//O(n2) time and O(1) solution
class Solution {
public int threeSumClosest(int[] nums, int target) {
//Sanity Check
if(nums==null || nums.length<3) return 0;
Arrays.sort(nums);
int sum = nums[0] + nums[1] + nums[2];
for(int i=0;i<nums.length-2;i++){
if(i>0 && nums[i]==nums[i-1]) continue;
int low = i+1, high = nums.length-1;
while(low<high){
int cursum = nums[low] + nums[high] + nums[i];
if(cursum==target){
return cursum;
}
else if(cursum<target){
if(Math.abs(cursum-target)<Math.abs(sum-target))
sum = cursum;
low++;
}
else{
if(Math.abs(cursum-target)<Math.abs(sum-target))
sum = cursum;
high--;
}
}
}
return sum;
}
}