Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created October 5, 2014 12:29
Show Gist options
  • Save sreeprasad/b0d36fdf3ce09c96ccaf to your computer and use it in GitHub Desktop.
Save sreeprasad/b0d36fdf3ce09c96ccaf to your computer and use it in GitHub Desktop.
3SumClosest
public int threeSumClosest(int[] num, int target) {
if( (num==null) || (num.length<3) ){
return target;
}
Arrays.sort(num);
int diff= Integer.MAX_VALUE;
int closest =0;
for(int i=0;i<num.length;i++){
int st=i+1;
int end=num.length-1;
while( (st<num.length) && (end>0) && (st<end) ){
int sum=num[i]+num[st]+num[end];
if(sum==target){
closest = sum;
diff =0;
break;
}else if(sum<target){
if( ((target-sum)<diff) ){
diff = target-sum;
closest =sum;
}
st++;
}else{
if( ((sum-target)<diff) ){
diff = sum-target;
closest =sum;
}
end--;
}
}
while( (i+1)<num.length && (num[i]==num[i+1]) ) i++;
}
return closest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment