题目:
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).
这道题要从一个数组中找到三个数字相加之和离target最近,其实跟3sum一毛一样的,只是把return改成了比较sum和target之间差距多少,懂了3sum以后做这道题是easy模式,所以就不多说了,会3sum一定会这道题,所以复习的时候去看3sum吧。
Runtime: 4 ms, faster than 78.56% of Java online submissions for 3Sum Closest.
Memory Usage: 38.4 MB, less than 6.67% of Java online submissions for 3Sum Closest.
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
if (nums.length < 3) {
throw new IllegalArgumentException("array length smaller than 3");
}
int result = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int pStart = i + 1;
int pEnd = nums.length - 1;
while (pStart < pEnd) {
int sum = nums[pStart] + nums[pEnd] + nums[i];
if (sum > target) {
pEnd--;
} else if (sum < target) {
pStart++;
} else {
return target;
}
if (Math.abs(sum - target) < Math.abs(result - target)) {
result = sum;
}
}
}
return result;
}
}
2024.6.27
就,咱也不知道,为啥这次还做错了。3sum倒是真记住了,但是不知道最近的脑子为啥给result initialize的时候想成了随便设一个值都行……最后debug了好久,fine。
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
int low = i + 1;
int high = nums.length - 1;
while (low < high) {
int sum = nums[i] + nums[low] + nums[high];
if (sum == target) {
return target;
} else if (sum < target) {
low++;
} else {
high--;
}
if (Math.abs(target - sum) < Math.abs(target - result)) {
result = sum;
}
}
}
return result;
}
}