題目
給定一個(gè)包括 n 個(gè)整數(shù)的數(shù)組 nums 和 一個(gè)目標(biāo)值 target。找出 nums 中的三個(gè)整數(shù)弧械,使得它們的和與 target 最接近八酒。返回這三個(gè)數(shù)的和。假定每組輸入只存在唯一答案刃唐。
例如羞迷,給定數(shù)組 nums = [-1,2画饥,1衔瓮,-4], 和 target = 1.
與 target 最接近的三個(gè)數(shù)的和為 2. (-1 + 2 + 1 = 2).
思路
- 定義結(jié)果值,再將數(shù)組排序
- 將sum值和結(jié)果值比較
- 將最接近的值返回
核心代碼
if (Math.abs(sum - target) < Math.abs(res - target)) { res = sum; }
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = nums[0] + nums[1] + nums[nums.length - 1];
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int start = i + 1, end = nums.length - 1;
while (start < end) {
int sum = nums[i] + nums[start] + nums[end];
if (sum > target) {
end--;
} else start++;
if (Math.abs(sum - target) < Math.abs(res - target)) {
res = sum;
}
}
}
return res;
}
}