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

这道题有点无力吐槽···

题目的意思是找出三个数之和跟target距离最接近的。

首先暴力求出三个数值和的所有情况,用一个value来记录当前最小的差是多少,然后如果有更小的就替换掉。

谁知道这样子得到的结果是Time Limit Exceeded

然后我加了句:f(tmpvalue==target)return target;

然后就ac了。

其实复杂度根本就没变化,如果target的最小目标恰好是最后三个,也是bad case的话,那么依然会超时。

但是这个有其他办法吗?

上代码

public class Solution {
    public int threeSumClosest(int[] num, int target) {
        
				Arrays.sort(num);
				int min=Integer.MAX_VALUE;
				int value=0;
				for(int index1=0;index1<num.length;++index1){
					if(index1!=0&&num[index1]==num[index1-1])continue;
					for(int index2=index1+1;index2<num.length;++index2){
						if(index2!=index1+1&&num[index2]==num[index2-1])continue;
						for(int index3=index2+1;index3<num.length;++index3){
							if(index3!=index2+1&&num[index3]==num[index3-1])continue;
							int tmpvalue=num[index1]+num[index2]+num[index3];
							if(tmpvalue==target)return target;
							if(Math.abs(tmpvalue-target)<min)
							{
								value=tmpvalue;
								min=Math.abs(value-target);
							}
						}
					}
				}
		    	return value;
    }
}


发布了42 篇原创文章 · 获赞 0 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章