Design a HashMap without using any built-in hash table libraries.
To be specific, your design should include these functions:
put(key, value)
: Insert a (key, value) pair into the HashMap. If the value already exists in the HashMap, update the value.get(key)
: Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.remove(key)
: Remove the mapping for the value key if this map contains the mapping for the key.
Example:
MyHashMap hashMap = new MyHashMap(); hashMap.put(1, 1); hashMap.put(2, 2); hashMap.get(1); // returns 1 hashMap.get(3); // returns -1 (not found) hashMap.put(2, 1); // update the existing value hashMap.get(2); // returns 1 hashMap.remove(2); // remove the mapping for 2 hashMap.get(2); // returns -1 (not found)
Note:
- All keys and values will be in the range of
[0, 1000000]
. - The number of operations will be in the range of
[1, 10000]
. - Please do not use the built-in HashMap library.
题意:
设计一个HashMap
Solution: LinkedList
初始化ListNode[]nodes = new ListNode[10000]。 size = 10000是题意要求。 那么,该ListNode[] 每个元素的default值为null。 这也是HashMap相比HashTable的优势:HashMap允许key为null。
举例,put(2,4), 用hashCode()算出对应在ListNode[]nodes中的坐标 i = 2
-->-->
若再put(2,9) , 则因为有相同的key, 之前的(2,4)会被覆盖成(2,9)
若再put(1002, 4), 用hashCode()算出对应在ListNode[]nodes中的坐标 i = 2。
-->-->
code
1 class MyHashMap { 2 /** Initialize your data structure here. */ 3 int size = 1000; 4 ListNode[] nodes = new ListNode[size]; 5 /** value will always be non-negative. */ 6 public void put(int key, int value) { 7 int i = hashId(key); 8 if (nodes[i] == null) 9 nodes[i] = new ListNode(-1, -1); 10 ListNode prev = find(nodes[i], key); 11 if (prev.next == null) 12 prev.next = new ListNode(key, value); 13 else prev.next.val = value; 14 } 15 /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ 16 public int get(int key) { 17 int i = hashId(key); 18 if (nodes[i] == null) 19 return -1; 20 ListNode node = find(nodes[i], key); 21 return node.next == null ? -1 : node.next.val; 22 } 23 /** Removes the mapping of the specified value key if this map contains a mapping for the key */ 24 public void remove(int key) { 25 int i = hashId(key); 26 if (nodes[i] == null) return; 27 ListNode prev = find(nodes[i], key); 28 if (prev.next == null) return; 29 prev.next = prev.next.next; 30 } 31 32 public int hashId(int key) { 33 return Integer.hashCode(key) % size; 34 } 35 36 ListNode find(ListNode bucket, int key) { 37 ListNode node = bucket, prev = null; 38 while (node != null && node.key != key) { 39 prev = node; 40 node = node.next; 41 } 42 return prev; 43 } 44 45 class ListNode { 46 int key, val; 47 ListNode next; 48 49 ListNode(int key, int val) { 50 this.key = key; 51 this.val = val; 52 } 53 } 54 }