时间: 2019-12-13 11:54 PM
题目地址: https://leetcode.com/problems/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.
给定一个由n个整数组成的数组nums和一个目标整数,请找到以nums为单位的三个整数,使总和最接近目标。 返回三个整数的和。 假设每个输入都只有一个解决方案。
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:
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int len = nums.length, result = 0, gap = Integer.MAX_VALUE;
for (int i = 0; i < len - 2; ++i) {
int j = i + 1, k = len - 1;
int remain = target - nums[i];
while (j < k) {
int sumjk = nums[j] + nums[k];
if (sumjk == remain) {
return target;
}
int gapTmp = remain - sumjk;
gapTmp = gapTmp > 0 ? gapTmp : -gapTmp;
if (gapTmp < gap) {
gap = gapTmp;
result = sumjk + nums[i];
}
if (sumjk < remain) {
++j;
} else {
--k;
}
}
}
return result;
}
Runtime: 3 ms, faster than 98.67% of Java online submissions for 3Sum Closest.
Memory Usage: 36.9 MB, less than 98.33% of Java online submissions for 3Sum Closest.