# 16. 3Sum Closest

XAMPP案例 933浏览

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).

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 + nums + nums;
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;
}
}