two pointers O(n^2)
public class Solution {
public int threeSumClosest(int[] num, int target) {
if (num == null || num.length <= 2) return 0;
Arrays.sort(num);
int closest = num[0] + num[1] + num[2];
for (int i = 0; i < num.length; i++) {
int p = i+1;
int q = num.length - 1;
while (p < q) {
int temp = num[i] + num[p] + num[q];
if (temp == target) {
return target;
}
if (temp < target) {
p++;
} else {
q--;
}
closest = Math.abs(temp - target) < Math.abs(closest - target) ? temp : closest;
}
}
return closest;
}
}