16. 3Sum Closest
Description
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Solution: (Java)
class Solution {
public int threeSumClosest(int[] nums, int target) {
int gap = Integer.MAX_VALUE;
int left, right, sum, result = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length-2; i++) {
if (i == 0 || nums[i] != nums[i-1]) {
left = i + 1;
right = nums.length - 1;
while (left < right) {
sum = nums[i] + nums[left] + nums[right];
if (sum == target)
return sum;
else if (sum > target) {
right--;
while (left < right && nums[right] == nums[right+1]) {
right--;
}
} else {
left++;
while (left < right && nums[left] == nums[left-1]) {
left++;
}
}
if (Math.abs(sum - target) < gap) {
gap = Math.abs(sum - target);
result = sum;
}
}
}
}
return result;
}
}
思路
题意为寻找三个数的和,使其最接近给定的target,本题思路与 LeetCode | 3Sum 类似,不一样的是:使用一个gap变量记录3个数的和与target的接近程度(即两者差的绝对值),寻找gap最小的那一组的和。还有就是left、right两个指针的移动:3个数的和大于target时,right指针向左移动;3个数的和小于target时,left指针向右移动。
博客围绕LeetCode的3Sum Closest问题展开,给定整数数组和目标值,需找出数组中三个整数,使其和最接近目标值。介绍了Java解法思路,与3Sum类似,用变量记录和与目标值接近程度,根据和与目标值大小移动指针。
2017

被折叠的 条评论
为什么被折叠?



