2 pointer
/*
time complexity: O(n^2)
space complexity: O(1)
note:res的区直
这里的res不能取Integer.MAX_VALUE,因为res可能overflow, 比如 res - targe (target < 0)
也不能直接取最小的nums[0],比如input:[0, 1, 2]
*/
class Solution {
public int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length < 2)
throw new IllegalArgumentException();
Arrays.sort(nums);
int res = nums[0] + nums[1] + nums[2];
for(int i = 0; i < nums.length - 2; i++) {
int low = i + 1, high = nums.length - 1;
while(low < high) {
int sum = nums[i] + nums[low] + nums[high];
if(target == sum){
return target;
} else if(sum > target) {
res = Math.abs(res - target) > Math.abs(sum - target) ? sum : res;
high--;
} else {
res = Math.abs(res - target) > Math.abs(sum - target) ? sum : res;
low++;
}
}
}
return res;
}
}