Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created December 24, 2012 16:22
Show Gist options
  • Save zac-xin/4369860 to your computer and use it in GitHub Desktop.
Save zac-xin/4369860 to your computer and use it in GitHub Desktop.
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.
public class Solution {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num);
int diff = Integer.MAX_VALUE;
int closest = Integer.MAX_VALUE;
for(int i = 0; i < num.length - 2; i++){
int k = i + 1;
int t = num.length - 1;
while( k < t){
if(num[i] + num[k] + num[t] == target){
return target;
}else if(num[i] + num[k] + num[t] < target){
int curDiff = target - num[i] - num[k] - num[t];
if(curDiff < diff){
closest = num[i] + num[k] + num[t];
diff = curDiff;
}
k++;
}else{
int curDiff = num[i] + num[k] + num[t] - target;
if(curDiff < diff){
closest = num[i] + num[k] + num[t];
diff = curDiff;
}
t--;
}
}
}
return closest;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment