您的位置:首页 > 其它

LeetCode 16. 最接近的三数之和

2019-04-22 16:09 417 查看
版权声明:本文为 renhq 原创文章,转载请注明出处: https://blog.csdn.net/qq_37499840/article/details/89453557

github:https://github.com/Renhongqiang/LeetCode

给定一个包括 n 个整数的数组 

nums
 和 一个目标值 
target
。找出 
nums
 中的三个整数,使得它们的和与 
target
 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

[code]例如,给定数组 nums = [-1,2,1,-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

思路:
三数之和:https://blog.csdn.net/qq_37499840/article/details/89453033

类比三数之和:依然排序,遍历nums,每次遍历为 nums[i] 设置 l=i+1、r=nums.length-1,l++、r--,使用rst记录目前最接近target的值,与遍历到的 nums[i] + nums[l] + nums[r] 比较,取二者中最接近 target 的值,然后判断 temp(三数和) 与 target 的大小关系,temp < target  则 l 右移,因为升序排序,否则  r 左移,如果相等则直接返回target。

[code]class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int rst = nums[0] + nums[1] + nums[2];
int l,r,temp;
for(int i = 0; i < nums.length - 2; i++)
{
l = i + 1;
r = nums.length - 1;
while(l < r)
{
temp = nums[i] + nums[l] + nums[r];
if(Math.abs(target - rst) > Math.abs(target - temp))
{
rst = temp;
}
if(temp > target)
r--;
else if(temp < target)
l++;
else
return target;
}
}
return rst;
}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: