链接:https://leetcode.cn/problems/3sum-closest/
题目:给你一个长度为 n 的整数数组 nums 和 一个目标值 target。从 nums 中选出三个整数,使它们的和与 target 最接近。返回这三个数的和。且题目确认唯一解。
思路:因为数组长度范围是1000,如果用暴力法n^3会超时,降低时间复杂度,对数组排序,遍历数组期间头尾指针查找三数和tempSum与target的差值,比较过程中有三种情况:
tempSum==target —>直接跳出程序,
tempSum<target —>左指针右移
tempSum>target —>右指针左
代码:
public static int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int distance = Integer.MAX_VALUE;
int result = Integer.MIN_VALUE;
for (int i=1;i<nums.length-1;i++){
int mid = nums[i];
int left = 0;
int right = nums.length-1;
// 使用头尾指针向中间遍历
inner:while (left<right){
// 下标重合
if (left==i||right==i){
break inner;
}
int tempSum = mid+nums[left]+nums[right];
if (Math.abs(tempSum-target)<distance){
distance=Math.abs(tempSum-target);
result=tempSum;
}
if (tempSum<target){
left++;
}else if (tempSum==target){
return tempSum;
}else {
right--;
}
}
}
return result;
}
作者小白,侵权请私信删
2022.11.07