- 最接近的三数之和
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum-closest
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 和三数之和类似, 只需要利用数组有序的特性来进行双指针移动即可
class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length < 3)
return 0;
//默认最接近是整数最大值
int minMinus = Integer.MAX_VALUE;
int res = 0;
//利用双指针,先排序
Arrays.sort(nums);
int h, t;
for(int i = 0; i < nums.length; i++) {
h = i + 1;
t = nums.length - 1;
while(h < t) {
int curNum = nums[i] + nums[h] + nums[t];
int minus = curNum - target;
if (minus == 0) {
return target;
} else {
//处理差距大小
if (Math.abs(minus) < minMinus) {
minMinus = Math.abs(minus);
res = curNum;
}
//处理h和t指针
if (minus > 0) t--;
if (minus < 0) h++;
}
}
}
return res;
}
}