什么时候才能顺应自己的内心而活
LeetCode官网:https://leetcode.com/
我是直接用GitHub授权登录的。
问题
给定一个n个整数的数组S,在S中找到三个整数,使得总和最接近给定数量的目标。返回三个整数的总和。你可以假设每个输入都有一个解决方案。
举例
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解法
public class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int n = nums.length;
int res = 0;
if (n <= 3) {
for (int num:nums)
res += num;
return res;
}
res = nums[0] + nums[1] + nums[2];
for (int i = 0; i <= n - 3; i++) {
int j = i + 1;
int k = n - 1;
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (Math.abs(target - res) >= Math.abs(target - sum)) {
res = sum;
if (res == target) return res;
}
if (sum > target) k--;
else if (sum < target) j++;
}
}
return res;
}
}