When input as below, the expected result should be 0, rather than -2147483647
[-2147483648, 2147483647 ,0 ,1]
1
Here is my solution (21 ms) to avoid overflow:
public int threeSumClosest(int[] nums, int target) {
assert nums!=null && nums.length >=3;
Arrays.sort(nums);
long minDiff = Integer.MAX_VALUE;
long clostest= Integer.MAX_VALUE;
long targetLong = (long)target;
for(int i=0; i<nums.length -2; i++) {
if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
int low = i + 1, high = nums.length - 1;
long sum, diff;
while (low < high) {
sum = (long)nums[i] + nums[low] + nums[high];
diff = sum - targetLong;
if( Math.abs(diff) <minDiff ) {
minDiff = Math.abs(diff);
clostest = sum;
}
if( diff == 0) {
return (int)clostest;
} else if(diff >0 ){
high--;
while (low<high && nums[high] ==nums[high+1]) high--;
} else {
low++;
while (low<high-1 && nums[low] ==nums[low-1]) low++;
}
}
}
}
return (int)clostest;
}