LeetCode, leetcodeoj
Given an array of integers, returnIndicesOf the two numbers such that they add up to a specific target.
You may assume that each input wowould 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].
Solution 1: Brute Force Search
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 }
Solution 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 }
A Hash table (also called a Hash table) is a data structure directly accessed based on the key. That is to say, It maps the key to a location in the table to access records to speed up the search. This ing function is called a hash function, and the array storing records is called a hash function. The hash table method is actually very simple, that is, to convert the key into an integer using a fixed algorithm function, that is, a hash function, and then perform the remainder operation on the array length, the remainder result is used as the subscript of the array, and the value is stored in the array space with the number as the base object. When a hash table is used for query, the hash function is used again to convert the key to the corresponding array subscript and locate the space to obtain the value, the array positioning performance can be fully utilized for data locating.
Core Method in solution 2
map.containsKey(complement)
The source code is as follows:
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; }
Well, I don't quite understand it !!