[LeetCode][1]Two Sum解析 -Java實現

Q:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

A:

以下解法和代碼沒有借閱以往任何資料,如果有更好的解法請在評論區留言

題目的意思是給一個數組,給一個特殊的數字,返回數組中相加等於目標數字的兩個索引,你可以假設每一個特殊數字都是單解。

public class TwoSum {
	public static int[] twoSum(int[] array,int target){
		for(int i=0;i<array.length;i++){
			for(int j = 0;j<array.length-i;j++){
				if((array[i]+array[j])==target)
					return new int[]{array[i],array[j]};
			}
		}
		return null;
	}
	public static void main(String[] args){
		int[] array = new int[]{1,2,3,4,5,6,7,8,9};
		int[] indices = TwoSum.twoSum(array, 5);
		if(indices!=null){
			System.out.println(indices[0]+"    "+indices[1]);
		}
	}
}
這是基礎解答,一般人第一反應應該都是這樣,這種方法遍歷兩次代價太高,我們可以具體解析一下看看有沒有更加便捷的解決方法。

只要我們取出array中的max和min,去掉array中大於target-min和小於target-max的數值,這樣可以縮減範圍,生成newarray。

那麼接下來我們只需要對有序序列newarray中的頭尾相加,如果大於target則把尾值去掉,如果小於target則把頭值去掉,這樣可以把兩次循環O(n^2)化爲O(2n)約等於O(n)

但是,這時候我們發現排序算法是O(n^2)的,所以這種解法就無解了。

另一種情況,我們把target的所有情況列出來一共有floor(target/2)種,我們只要維護這樣一個數組targetArray[0-target]只要targetArray[i]>=1且targetArray[target-i]>=1即可返回。(假設array中沒有負數)

代碼如下

	public static int[] newTwoSum(int[] array,int target){
		int[] targetArray = new int[target+1];
		for(int i :array){
			if(i>=0&&i<=target){
				targetArray[i]++;
				if(targetArray[target-i]>=1){
					return new int[]{i,target-i};
				}
			}
		}
		return null;
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章