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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
看到這個大部分人都很直覺地會想到透過兩個for loop
把所有組合窮舉出來
這樣做法的時間複雜度是O(n),空間複雜度O(1)
public int[] twoSum(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] == target - nums[i]) { return new int[] { i, j }; } } } throw new IllegalArgumentException("No two sum solution"); }
那麼如果使用了Map呢(Map<key, value>)
Map是透過雜湊表(hash table)把我們所input的key轉換為value
我把他簡化理解成查表(look-up table)的意思
反正今天給我一個key我可以找到一個對應的value
也因為這樣類似查表的特性,他找尋的速度是O(1)
所以剛剛的問題利用Map可以在O(n)裡解出
不過付出的代價就是要有儲存map的空間,複雜度是O(n)
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[] { i, map.get(complement) }; } } throw new IllegalArgumentException("No two sum solution"); }