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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章