hashmap: store = new // deque{{k, v}}[] add(k, v): i = index(k) dq = store[i] if dq == null: dq = new dq() store[i] = dq for kv in dq: if kv.key == k: kv.value = v return dq.enqueue(new {k, v}) bool hasKey(k): dq = store[index(k)] if dq == null: return false for kv in dq: if kv.key == k: return true return false bool removeKey(k): i = index(k) dq = store[i] if dq == null: return false // dq.nodes() is a copy for node in dq.nodes(): if node.kv.key == k: dq.removeNode(node) if dq.isEmpty(): store[i] = null return true return false // O(n) bool remove(v): for i = 0, i < store.length(), i++: dq = store[i] if dq == null: continue // dq.nodes() is a copy for node in dq.nodes(): if node.kv.value == v: dq.removeNode(node) if dq.isEmpty(): store[i] = null return true return false // helpers int index(k): return hash(k) %store.length() int hash(k): if k == null: throw // ...
Wednesday, November 01, 2017
implement hashmap
k cannot be null as cannot calculate hash of k.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment