Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Subscribe to see which companies asked this question
public class Solution {
int keepDec(int i, int[] nums){
--i;
while(i>=0 && nums[i]==nums[i + 1]){
--i;
}
return i;
}
int keepInc(int i, int[] nums){
++i;
while(i= 0 && y < len){
int sum = nums[i] + nums[x] + nums[y];
if(Math.abs(sum - target) < Math.abs(res - target)){
res = sum;
}
if(sum == target){
return target;
}
else if( sum > target){
y = keepDec(y, nums);
}else{
x = keepInc(x, nums);
}
}
i = keepInc(i, nums);
}
return res;
}
}
No comments:
Post a Comment