3Sum Closest
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.
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).
public class Solution {
public int threeSumClosest(int[] num, int target) {
// Start typing your Java solution below
// DO NOT write main() function
Arrays.sort(num);
ArrayList> list = new ArrayList>();
Integer closest = null;
for (int i = 0; i <= num.length - 3; i++) {
int a = num[i];
int j = i+1;
int k = num.length - 1;
if (closest == null) closest = a + num[j] + num[k];
int best = closest.intValue();
while (j < k) {
int b = num[j];
int c = num[k];
if (a + b + c == target) {
return a + b + c;
}
else if (a + b + c < target) {
if (Math.abs(a + b + c - target)
< Math.abs(best - target)) {
best = a + b + c;
}
j++;
}
else {
if (Math.abs(a + b + c - target)
< Math.abs(best - target)) {
best = a + b + c;
}
k--;
}
}
if (Math.abs(best - target) < Math.abs(closest.intValue() - target)) {
closest = best;
}
}
return closest.intValue();
}
}
No comments:
Post a Comment