乐趣区

16. 3Sum Closest

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).
难度:medium
题目:给定一整数数组和一整数,找出三个数之和最接近目标整数并返回其和。假定输入只有一个匹配的答案。
思路:先排序,固定一个数,然后剩下的数组两边夹挤。
Runtime: 10 ms, faster than 86.09% of Java online submissions for 3Sum Closest.Memory Usage: 27 MB, less than 16.46% of Java online submissions for 3Sum Closest.
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
int result = nums[0] + nums[1] + nums[2];
int distance = Math.abs(result – target);
for (int i = 0; i < n – 2; i++) {
int left = i + 1;
int right = n – 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == target) {
return target;
}
if (sum > target) {
right–;
} else {
left++;
}

if (Math.abs(sum – target) < Math.abs(distance)) {
distance = Math.abs(sum – target);
result = sum;
}
}
}

return result;
}
}

退出移动版