|
| 1 | +class MyHashMap { |
| 2 | + private class Node { |
| 3 | + private int key, value; |
| 4 | + |
| 5 | + public Node(int k, int v) { |
| 6 | + key = k; |
| 7 | + value = v; |
| 8 | + } |
| 9 | + } |
| 10 | + |
| 11 | + private Node[] map; |
| 12 | + private int size, maxSize; |
| 13 | + private double loadCapacity; |
| 14 | + |
| 15 | + /** Initialize your data structure here. */ |
| 16 | + public MyHashMap() { |
| 17 | + size = 0; |
| 18 | + maxSize = 512; |
| 19 | + loadCapacity = 0.66; |
| 20 | + map = new Node[maxSize]; |
| 21 | + } |
| 22 | + |
| 23 | + private int getHash(int key) { |
| 24 | + return key % map.length; |
| 25 | + } |
| 26 | + |
| 27 | + private void resize() { |
| 28 | + if (size < (int) (maxSize * loadCapacity)) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + maxSize *= 2; |
| 33 | + size = 0; |
| 34 | + |
| 35 | + Node[] temp = map; |
| 36 | + map = new Node[maxSize]; |
| 37 | + |
| 38 | + for (Node n : temp) { |
| 39 | + if (n == null || n.key == -1) { |
| 40 | + continue; |
| 41 | + } |
| 42 | + put(n.key, n.value); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /** value will always be non-negative. */ |
| 47 | + public void put(int key, int value) { |
| 48 | + int idx = getHash(key); |
| 49 | + |
| 50 | + while (map[idx] != null && map[idx].key != key) { |
| 51 | + ++idx; |
| 52 | + idx %= maxSize; |
| 53 | + } |
| 54 | + |
| 55 | + if (map[idx] != null) { |
| 56 | + map[idx].value = value; |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + map[idx] = new Node(key, value); |
| 61 | + ++size; |
| 62 | + |
| 63 | + resize(); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Returns the value to which the specified key is mapped, or -1 if this map |
| 68 | + * contains no mapping for the key |
| 69 | + */ |
| 70 | + public int get(int key) { |
| 71 | + int idx = getHash(key); |
| 72 | + |
| 73 | + while (map[idx] != null) { |
| 74 | + if (map[idx].key == key) { |
| 75 | + return map[idx].value; |
| 76 | + } |
| 77 | + |
| 78 | + ++idx; |
| 79 | + idx %= maxSize; |
| 80 | + } |
| 81 | + |
| 82 | + return -1; |
| 83 | + } |
| 84 | + |
| 85 | + /** |
| 86 | + * Removes the mapping of the specified value key if this map contains a mapping |
| 87 | + * for the key |
| 88 | + */ |
| 89 | + public void remove(int key) { |
| 90 | + int idx = getHash(key); |
| 91 | + |
| 92 | + while (map[idx] != null) { |
| 93 | + if (map[idx].key == key) { |
| 94 | + // Mark the current spot as "deleted" since we |
| 95 | + // might have had multiple collisions for keys |
| 96 | + // that should have came before it and are placed |
| 97 | + // after it since we're using Linear Probing! |
| 98 | + map[idx] = new Node(-1, -1); |
| 99 | + --size; |
| 100 | + |
| 101 | + return; |
| 102 | + } |
| 103 | + |
| 104 | + ++idx; |
| 105 | + idx %= maxSize; |
| 106 | + } |
| 107 | + } |
| 108 | +} |
0 commit comments