前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[LeetCode][Java] 3Sum Closest「建议收藏」

[LeetCode][Java] 3Sum Closest「建议收藏」

作者头像
全栈程序员站长
发布2022-07-07 20:51:18
2040
发布2022-07-07 20:51:18
举报

大家好,又见面了,我是全栈君。

题目:

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

代码语言:javascript
复制
    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

题意:

给定一个包括n个整数的数组S,在数组中找出三个整数。使得这三个整数的和与目标值最为接近。

返回这三个整数的和。你能够假定对于每一个整数。都有确定的一个解。

代码语言:javascript
复制
    For example, given array S = {-1 2 1 -4}, and target = 1.

    The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

算法分析:

參考博客:http://www.zhuangjingyang.com/leetcode-3sum/

和3Sum异曲同工。 只是这里我们要推断的条件不在是三个数字和为0而是和为一个更加接近target的数字。

我们依旧採用3Sum的算法,若有三个数字x1 + x2 + x3 = result 我们所求的便是让result最接近target。

因此对于num,首先排序。然后遍历每一个数字其下标大于自身的两个数字。然后设置两个全局变量 一个 minVal 用于记录其与target的距离,当距离减小时便更新result的新值。

AC代码:

代码语言:javascript
复制
<span style="font-size:12px;">public class Solution 
{
	private  int minVal = Integer.MAX_VALUE;
	private  int result = 0;
    public  int threeSumClosest(int[] num, int target) 
    {
    	Arrays.sort(num);
    	//if number is less than 3 or num is null it's can't be calc
    	if(num.length <3 ||  num ==null)
    		return target;
    	for(int i=0;i<num.length;i++)
    	{
    		if(i>0 && num[i] == num[i-1])
    			continue;
    		find(i,num,num[i],target);
    	}
    	return result;
    }
    public  void find(int index,int[] num,int target,int res)
    {
    	int l = index+1; //low is equal to index+1 just because we just search element that is bigger than itself
    	int r = num.length - 1;
    	while(l<r)
    	{
    		if( Math.abs(num[l] + num[r] + target - res) <= minVal)
    		{
    			minVal = Math.abs(num[l] + num[r] + target - res);//it's more closer
    			result = num[l] + num[r] + target;
    		}
    		if(num[l] + num[r] + target >res)
    			r--;
    		else
    			l++;
    	}
    }
}</span>

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/116237.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年1月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目:
  • 题意:
  • 算法分析:
  • AC代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档