For some emotional and schedule issues, I have been absent for two days. But there shouldn't be any excuse for this. So, I would make up as soon as possible!
DESCRIPTION:
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).
ANALYSIS:
At beginning, I have no idea to solve this problem. So, I have to look the top solution.
And two days later, I borrow the thread and code on my own. Finally, AC!
The core idea: 'loop for the min number of three from 0 to length-1', 'use two point(so-called '游标') for middle number(starti) and max number(endi)', 'compare the abs of current sum and closest'
SOLUTION:
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int closest=nums[0]+nums[1]+nums[2];
for(int i=0;i<nums.length-2;i++){
int starti=i+1;
int endi=nums.length-1;
int sum=nums[i]+nums[starti]+nums[endi];
while(starti<endi){
sum=nums[i]+nums[starti]+nums[endi];
if(Math.abs(sum-target)<Math.abs(closest-target))
closest=sum;
if(sum==target)
return target;
else if(sum<target){
starti++;
}else if(sum>target){
endi--;
}
}
}
return closest;
}