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 ex ...
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
解法1:暴力搜索
1 public int[] twoSum(int[] nums, int target) { 2 for (int i = 0; i < nums.length; i++) { 3 for (int j = i + 1; j < nums.length; j++) { 4 if (nums[j] == target - nums[i]) { 5 return new int[] { i, j }; 6 } 7 } 8 } 9 }
解法2:Hash Table
1 public int[] twoSum(int[] nums, int target) { 2 Map<Integer, Integer> map = new HashMap<>(); 3 for (int i = 0; i < nums.length; i++) { 4 int complement = target - nums[i]; 5 if (map.containsKey(complement)) { 6 return new int[] { map.get(complement), i }; 7 } 8 map.put(nums[i], i); 9 } 10 }
哈希表(Hash table,也叫散列表),是根據key而直接進行訪問的數據結構。也就是說,它通過把key映射到表中一個位置來訪問記錄,以加快查找的速度。這個映射函數叫做散列函數,存放記錄的數組叫做散列表。哈希表的做法其實很簡單,就是把key通過一個固定的演算法函數即所謂的哈希函數轉換成一個整型數字,然後就將該數字對數組長度進行取餘,取餘結果就當作數組的下標,將value存儲在以該數字為下標的數組空間里。而當使用哈希表進行查詢的時候,就是再次使用哈希函數將key轉換為對應的數組下標,並定位到該空間獲取value,如此一來,就可以充分利用到數組的定位性能進行數據定位。
解法2中的核心方法
map.containsKey(complement)
其源碼如下:
public boolean containsKey(Object key) { return getNode(hash(key), key) != null; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
嗯,看不太明白!!