美文网首页
design hashmap

design hashmap

作者: messy_code | 来源:发表于2019-01-12 18:37 被阅读0次

leetcode地址

package main

import (
    "fmt"
)

const (
    size = 10
)

type MyHashMap struct {
    arr []*MyLinkedList
}
type MyLinkedList struct {
    k, v int
    next *MyLinkedList
}

/** Initialize your data structure here. */
func Constructor() MyHashMap {
    return MyHashMap{
        arr: make([]*MyLinkedList, size),
    }
}

/** value will always be non-negative. */
func (this *MyHashMap) Put(key int, value int) {
    this.Remove(key)
    cll := this.arr[key%size]
    nll := &MyLinkedList{
        k: key,
        v: value,
    }
    if cll != nil {
        nll.next = cll
    }
    this.arr[key%size] = nll
}

/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
func (this *MyHashMap) Get(key int) int {
    cll := this.arr[key%size]
    for cll != nil {
        if cll.k == key {
            return cll.v
        }
        cll = cll.next
    }
    return -1
}

/** Removes the mapping of the specified value key if this map contains a mapping for the key */
func (this *MyHashMap) Remove(key int) {
    cll := this.arr[key%size]
    var pre *MyLinkedList
    for cll != nil {
        if cll.k == key {
            if pre == nil && cll.next == nil {
                this.arr[key%size] = nil
            } else if pre == nil && cll.next != nil {
                this.arr[key%size] = cll.next
            } else if pre != nil && cll.next == nil {
                pre.next = nil
            } else if pre != nil && cll.next != nil {
                pre.next = cll.next
            }
            break
        }
        pre = cll
        cll = cll.next
    }
}

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

func main() {
    obj := Constructor()
    obj.Put(1, 2)
    obj.Put(2, 4)
    obj.Put(11, 6)
    obj.Put(4, 8)
    param_2 := obj.Get(1)
    fmt.Println(param_2)
    obj.Remove(1)
    param_2 = obj.Get(1)
    fmt.Println(param_2)
    fmt.Println(obj)
    fmt.Println(obj)

}

相关文章

网友评论

      本文标题:design hashmap

      本文链接:https://www.haomeiwen.com/subject/jnvcdqtx.html