Created
January 19, 2015 15:59
-
-
Save Maggie199/c439e9ba12bf94c11c14 to your computer and use it in GitHub Desktop.
Leetcode #16
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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