本文共 1947 字,大约阅读时间需要 6 分钟。
为了找到数组中三个整数,使其和与目标值最接近,我们可以采用以下步骤:
以下是具体的实现代码:
import java.util.Arrays;class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int len = nums.length; int closest = Integer.MAX_VALUE; // 检查前三个和后三个的和 int firstSum = nums[0] + nums[1] + nums[2]; if (target <= firstSum) { return firstSum; } int lastSum = nums[len - 3] + nums[len - 2] + nums[len - 1]; if (target >= lastSum) { return lastSum; } // 遍历数组,使用双指针技巧 for (int a = 0; a <= len - 3; a++) { // 跳过重复的元素 if (a > 0 && nums[a] == nums[a - 1]) { continue; } int b = a + 1; int c = len - 1; while (b < c) { int currentSum = nums[a] + nums[b] + nums[c]; if (currentSum == target) { return target; } int diffCurrent = Math.abs(target - currentSum); int diffClosest = Math.abs(target - closest); if (diffCurrent < diffClosest) { closest = currentSum; } else if (diffCurrent == diffClosest) { // 保持和为正数的顺序,避免不必要的重复 if (currentSum > closest) { closest = currentSum; } } // 根据当前和与目标的比较,移动指针 if (currentSum < target) { b++; } else { c--; } } } return closest; }}
这个代码首先对数组进行排序,然后使用双指针技巧来找到三个数的和与目标值最接近的情况。通过这种方法,我们能够高效地解决问题,避免了暴力枚举所有可能的三元组,显著提高了性能。
转载地址:http://xjgr.baihongyu.com/