题目:
给定一个包括n个整数的数组nums和一个目标值target。找到nums中的三个整数,使得他们之和与target最为接近。返回三个整数之和,假定每组输入只存在唯一答案
解题思路:
将nums数组重新排列,然后从i = 0开始遍历,分别取left = i + 1和right = nums.length - 1,将nums[i]、nums[left]和nums[right]三数之和与target差值的绝对值与diff比较,如果小于diff,则使sum赋值为此三数之和,并且将diff的值修改为三数之和与target差值的绝对值
class Solution {
public int threeSumClosest(int[] nums, int target) {
int diff = Integer.MAX_VALUE, result = 0;
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == target) {
return sum;
}
if (diff > Math.abs(target - sum)) {
diff = Math.abs(target - sum);
result = sum;
}
if (sum > target) { //因为sum > target,因此只需将right向左调整,此时sum的值则会减少,这样才能找到更接近的target的三数之和
right--;
} else {
left++; //因为sum <= target,因此只需将left向右调整,此时sum的值则会增加,这样才能找到更接近target的三数之和
}
}
}
return result;
}
}