Two Sum Closest
Given an arraynumsof n _integers, find two integers in _nums _such that the sum is closest to a given number,_target.
Return the difference between the sum of the two integers and the target.
Example
Given arraynums=[-1, 2, 1, -4], andtarget=4.
The minimum difference is1. (4 - (2 + 1) = 1).
Solution:
public int twoSumCloset(int[] nums, int target) {
if(nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int left = 0, right = nums.length - 1;
int res = Integer.MAX_VALUE;
int minDiff = Integer.MAX_VALUE;
while(left < right) {
int sum = nums[left] + nums[right];
int diff = Math.abs(sum - target);
if(diff <= minDiff) {
res = sum;
minDiff = diff;
}
if(sum > target) {
right--;
}
else {
left++;
}
}
return minDiff;
}