Skip to content

Instantly share code, notes, and snippets.

@Maggie199
Created January 19, 2015 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maggie199/c439e9ba12bf94c11c14 to your computer and use it in GitHub Desktop.
Save Maggie199/c439e9ba12bf94c11c14 to your computer and use it in GitHub Desktop.
Leetcode #16
public int threeSumClosest(int[] num, int target) {
HashSet<Integer> partSum = new HashSet<Integer>();
partSum.add(num[0]+num[1]);
int result=num[0]+num[1]+num[2];
for(int i=2; i<num.length; i++){
for(int n: partSum){
if(Math.abs(n+num[i]-target)<Math.abs(result-target)){
if(n+num[i] == target)
return target;
else result = n+num[i];
}
}
for(int j=i-1; j>=0; j--){
partSum.add(num[i]+num[j]);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment