两数和的最接近值
题目:
描述
给定整数数组num,从中找到两个数字使得他们和最接近target,返回两数和与 target 的差的 绝对值。
样例
样例1
输入: nums = [-1, 2, 1, -4] 并且 target = 4
输出: 1
解释:
最小的差距是1,(4 - (2 + 1) = 1).
样例2
输入: nums = [-1, -1, -1, -4] 并且 target = 4
输出: 6
解释:
最小的差距是6,(4 - (- 1 - 1) = 6).
public class Solution {
/**
* @param nums: an integer array
* @param target: An integer
* @return: the difference between the sum and the target
*/
public int twoSumClosest(int[] nums, int target) {
// write your code here
Arrays.sort(nums);
int l = 0, r = nums.length - 1;
int min = Integer.MAX_VALUE;
while(l < r) {
int sum = nums[l] + nums[r];
int diff = Math.abs(sum - target);
min = Math.min(diff, min);
if(sum > target) {
r--;
} else if(sum < target) {
l++;
} else {
break ;
}
}
return min;
}
}