最新消息:XAMPP默认安装之后是很不安全的,我们只需要点击左方菜单的 "安全"选项,按照向导操作即可完成安全设置。

16. 3Sum Closest

XAMPP案例 admin 1416浏览 0评论

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

转载请注明:XAMPP中文组官网 » 16. 3Sum Closest

您必须 登录 才能发表评论!