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).
Idea: First sort the array. Use three pointers (i,j,k) to denote the three integers. Fix i, and use j,k to maintain a sliding window. If num[i]+num[j]+num[k]<target, move the left pointer forward, otherwise move the right pointer backward. Since there may be duplicated elements in the array, skip them to avoid repeated calculation, although this will not reduce the worst case time complexity.
Time: O(n^2) Space: O(1)
Code:
public class Solution {
public int threeSumClosest(int[] num, int target) {
int closestSoFar=num[0]+num[1]+num[2];
Arrays.sort(num);
for(int i=0;i<num.length-2;i++)
{
if(i>0&&num[i]==num[i-1])
continue;
int j=i+1;
int k=num.length-1;
while(j<k)
{
int curSum=num[i]+num[j]+num[k];
if(curSum==target)
return target;
else if(curSum<target)
{
j++;
while(j<k&&num[j]==num[j-1])
j++;
}
else
{
k--;
while(j<k&&num[k]==num[k+1])
k--;
}
if(Math.abs(target-closestSoFar)>Math.abs(target-curSum))
closestSoFar=curSum;
}
}
return closestSoFar;
}
}
No comments:
Post a Comment