解题思路:这道题和3个数和为指定数很相似,主要是固定一个数,然后计算三数之和,如果和大于指定数,调整右指针向左移动,如果小于指定数,左指针向右移动。过程中记录和指定数相减最小的的和
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);int diff = Integer.MAX_VALUE, closest = 0;
for (int k=0; k<nums.length-2; ++k) {
for (int i=k+1, j=nums.length-1; i<j; ) {
int sum = nums[k] + nums[i] + nums[j];
if (sum == target) { return target; }
else if (sum > target) {
if (sum-target < diff) {
diff = sum-target;
closest = sum;
}
--j;
} else {
if (target-sum < diff) {
diff = target-sum;
closest = sum;
}
++i;
}
}
}
return closest;
}
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。