leetcode数组专项习题:3数组合最近值

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88178020

14、3数组合最近值
3sum-closest: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).
题目要求:给定有n个整数的数组S,在S中找到三个整数,使得总和最接近给定数字target。 返回三个整数的总和。可以假设每个输入都只有一个解决方案。
例如,给定数组S = {-1 2 1 -4},并且target = 1。
最接近目标的总和是2.(-1 + 2 + 1 = 2)。
分析:最简单的解法是暴力求解,用diff记录最佳方案的绝对值差,遍历每一种可能的三个数字组合值,一一比较,选取diff最小的组合返回。
代码如下:

public class Solution{
    public static void main(String[] args) 
    {
    	Solution sl = new Solution();
    	int target = -1;
    	int[] num= {-3,-2,-5,3,-4};
    	int sum=sl.threeSumClosest(num, target);
    	System.out.println(sum);
     }
     
    public int threeSumClosest(int[] num, int target) 
    {
        int len=num.length;
        int sum=num[0]+num[1]+num[2];
        int diff=Math.abs(target-sum);
        for(int i=0;i<len;i++)
        {
        	for(int j=i+1;j<len;j++)
        	{
        		for(int k=j+1;k<len;k++)
        		{
        			int tempsum =num[i]+num[j]+num[k];
        			if (diff>Math.abs(tempsum-target))
        			{
        				sum=tempsum;
        				diff=Math.abs(tempsum-target);
        			}
        		} 
        	}
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88178020