/** Initialize your data structure here. */ publicMyHashMap(){ } /** value will always be non-negative. */ publicvoidput(int key, int value){ int i = index(key); if (buckets[i] == null) { buckets[i] = new Bucket(); } ListNode node = find(buckets[i], key); if (node.next == null) { node.next = new ListNode(key, value); } else { node.next.val = value; } } /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */ publicintget(int key){ int i = index(key); if (buckets[i] == null) { return -1; } ListNode node = find(buckets[i], key); return node.next == null ? -1 : node.next.val; } /** Removes the mapping of the specified value key if this map contains a mapping for the key */ publicvoidremove(int key){ int i = index(key); if (buckets[i] == null) { return; } ListNode node = find(buckets[i], key); if (node.next == null) { return; } node.next = node.next.next; } }
classBucket{ final ListNode head = new ListNode(-1, -1); }
classListNode{ int key, val; ListNode next;
ListNode(int key, int val) { this.key = key; this.val = val; } } /** * Your MyHashMap object will be instantiated and called as such: * MyHashMap obj = new MyHashMap(); * obj.put(key,value); * int param_2 = obj.get(key); * obj.remove(key); */
func (this *MyHashMap) hash(key int) int { return key % base }
func (this *MyHashMap) Put(key int, value int) { hash := this.hash(key) for e := this.data[hash].Front(); e != nil ; e = e.Next() { if now := e.Value.(entry); now.key == key { e.Value = entry{key, value} return } } this.data[hash].PushBack(entry{key, value}) }
func (this *MyHashMap) Get(key int) int { hash := this.hash(key) for e := this.data[hash].Front(); e != nil ; e = e.Next() { if now := e.Value.(entry); now.key == key { return now.value } } return -1 }
func (this *MyHashMap) Remove(key int) { hash := this.hash(key) for e := this.data[hash].Front(); e != nil ; e = e.Next() { if now := e.Value.(entry); now.key == key { this.data[hash].Remove(e) } } }
/** * Your MyHashMap object will be instantiated and called as such: * obj := Constructor(); * obj.Put(key,value); * param_2 := obj.Get(key); * obj.Remove(key); */