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

题目:

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.

   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考试。 一定要坚持!!!

点赞