public class Solution {
public int threeSumClosest(int[] num, int target) {
Arrays.sort(num);
// Two pointers scan
int closest = num[0] + num[1] + num[2];
for(int i = 0; i < num.length - 2; i++) {
int left = i + 1, right = num.length - 1;
int sum = 0, closestSum = 0;
boolean isFirst = true;
while(left < right) {
sum = num[i] + num[left] + num[right];
if(sum == target) {
return target;
} else if(sum < target) {
left++;
} else {
right--;
}
if(isFirst == true) {
closestSum = sum;
isFirst = false;
// Updates the closest every loop
} else if(Math.abs(target - sum) < Math.abs(target - closestSum)) {
closestSum = sum;
}
}
if(Math.abs(target - closestSum) < Math.abs(target - closest)) {
closest = closestSum;
}
}
return closest;
}
}
Time: O(n^2)
Space: O(1)