题目:
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.
与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).
题解:
1.先将数组排序 O(nlogn)
2.排序好后,使用双指针法先固定一个数start 然后 前指针 start +1 最后指针 end-1
如果sum = nums[start] + nums[start+1] + nums[end-1];
sum > target end–; sum < target start ++; sum == target 直接返回
最后直接返回即可
代码
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int result = 0; //返回的结果
int compare = Integer.MAX_VALUE; // 比较的值
int sum = 0;
int len = nums.length;
for(int i = 0; i <len-2; i++){
int end = len - 1;
int start = i + 1;
while(start != end){
sum = nums[i]+ nums[start]+ nums[end];
if(sum == target){
return sum;
}else if(sum < target){
if(Math.abs(target-sum)<compare){
compare = Math.abs(target-sum);
result =sum;
}
start++;
}else{
if(Math.abs(target-sum)<compare){
compare = Math.abs(target-sum);
result =sum;
}
end--;
}
}
}
return result;
}
}
本文介绍了一种解决特定编程问题的算法:给定数组和目标值,找到数组中三个数的和最接近目标值的方法。通过排序和双指针技巧,实现高效查找。
1766

被折叠的 条评论
为什么被折叠?



