1. 程式人生 > >LeetCode(一)————Two Sum

LeetCode(一)————Two Sum

LeetCode的第一篇文章,希望通過這個系列的筆記能夠提升自己的編碼能力和演算法能力。

問題描述(原文):

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, and you may not use the same element twice.

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0
] + nums[1] = 2 + 7 = 9, return [0, 1].

本人翻譯:給你個int陣列,返回兩個相加等於特定值的陣列元素下標。你可以假設每個輸入都會有一個確定的解決方法,也可能不會用兩次相同的元素。說實話最後半句我也沒明白啥意思,如果有知道的,可以在文章下邊留言,many thanks.

Solution:

public int[] twoSum(int[] nums, int target) {
		Map<Integer, Integer> mapping = new HashMap<>();
		int[] indesx = new int[2];
		for (int i = 0; i < nums.length; i++) {
			mapping.put(nums[i], i);
		}

		for (int i = 0; i < nums.length; i++) {
			int complement = target - nums[i];
			if (mapping.containsKey(complement) && mapping.get(complement) != i) {
				indesx[0] = nums[i];
				indesx[1] = complement;
			}
		}

		return indesx;
	}

總結:

在這裡宣告一下,雖然文章是原創,但是Solution並非我寫的程式碼,上段程式碼引用了LeetCode上此問題支援率最高的解決方法。

看到題目的時候我是正常的用了二重for迴圈進行求解的,在LeetCode中也有我那種解法,他們稱之為:Brute Force。

而上面貼出來的這種解法思路在於考慮到了時間複雜度。這裡又不得不記錄一下我收集到了對時間複雜度的理解:

基本操作執行次數與問題規模n成正比。時間複雜度(又叫漸進時間複雜度,我的理解其實就是求極限值)共有八個同數量級分別是:1,log2n,n,n log2n,n^2,n^3,2^n,n!   從1到n!時間複雜度以此增高。二重for迴圈記作O(n^2),三重for迴圈記作O(n^3)以此類推。

解釋是這樣的:To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.

為了改進我們執行時間的複雜程度,我們需要更有效的方法去array中檢查是否有一個特定的“補足數”存在,如果存在,我們就去找他的index。那麼維護陣列元素與其下標之間的對映關係最好的途徑是什麼呢?沒錯,就是hash table。

這句話給我的印象特別深。那麼如果下一次又出現一個問題要求我們找到兩組值的對應關係的話,我們首先就會考慮到雜湊表。這正是我希望得到的東西,一種思考的方向。

We reduce the look up time from O(n) to O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say "near" because if a collision occurred, a look up could degenerate to O(n) time. But look up in hash table should be amortized O(1) time as long as the hash function was chosen carefully.

我們通過犧牲空間換取速度的方式來將時間複雜度從O(n)到O(1)。雜湊表的建立正是為此目的,它支援在近乎不變的時間內快速查詢。

後面我就不翻譯了,因為我並沒有理解他的意思。有興趣的朋友歡迎文章下方留言。不勝感激。

===================================================================================================================

2017-7-2,補充

剛剛在研究HashSet的時候得知了HashSet的相關特性,不允許重複的元素,允許null值,等等,不過這不是關鍵,關鍵的是返回來看HashMap,原來也是不能有重複Key的,如果有相同的Key,那麼就會被新的Key所覆蓋。因此,這就可以解釋you may not use the same element twice.這句話了,如果有重複的int數值,那麼就會產生覆蓋的問題。