Februari 9, 2022

Leet Code - 706 - Design HashMap

Question

https://leetcode.com/problems/design-hashmap/

Solution (Golang)

type MyHashMap struct {
    Data[] int
}


func Constructor() MyHashMap {
    // create int array with size of 10^6 + 1 (0 <= key, value <= 10^6)
    return MyHashMap Data: make([] int, 1000001)}
}


func(this *MyHashMap) Put(key int, value int) {
    // default value is 0, so we need to add value with 1
    this.Data[key] = value + 1
}


func(this *MyHashMap) Get(key int) int {
    // default value is 0, so we need to subtract value with 1
    return this.Data[key] - 1
}


func(this *MyHashMap) Remove(key int) {
    // remove key by assigning 0 value
    this.Data[key] = 0
}


/**
 * Your MyHashMap object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Put(key,value);
 * param_2 := obj.Get(key);
 * obj.Remove(key);
 */