LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和

题目:

Given an arraySofnintegers, find three integers inSsuch 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.

   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).

翻译:给定一个nums整型数组,和一个目标和target,找出数组中三个数的和最接近target,返回这个和即可

思路:和threeSum差不多,只不过不用标记这三个数的位置,只需返回三个数的和与target 相差的最小值。

求和的时候采用Twosum做法,此时target = target -num[i];然后返回2个数的和与新的target相差的最小值

注意: 表示相差最小值的时候 一定要用绝对值。即Math.abs()。


代码:

 public static int threeSumClosest(int[] nums, int target) {
        if(nums == null || nums.length < 3)
        	return Integer.MIN_VALUE;
        Arrays.sort(nums);
        int min = nums[0] +  nums[1] + nums[2] - target;//最小间距
        for(int i = 0 ; i < nums.length-2;i++)//保证nums.length-1 和nums.length-2
        {
        	int close= twoSum(nums,i+1,target -nums[i]);//计算剩下2个数最接近值
        	if(Math.abs(min) > Math.abs(close))
        		min = close;
        }
        return target+min;

    }
	public static int twoSum(int []num,int start, int target)
	{
		int min = num[start] + num[start+1] -target;//找到最小间距
		int l = start;
		int r = num.length-1;
		while(l < r)
		{
			if(num[l]+num[r]==target)//如果等于返回
				return 0;
			int close = num[l] + num[r] -target;
			if(Math.abs(close) <Math.abs(min))
				min = close;
			if(num[l]+num[r] > target)
			{
				r--;
			}
			else l++;
		}
		
		return min;
		
	}
最近复习网络安全,加上五一放假,刷题断了一些天,罪过罪过!

无奈过些日子还有UML考试。 一定要坚持!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值