采用取模散列+双链表+桶的思想

    1. const buckets int = 233
    2. type entry struct {
    3. key, val int
    4. }
    5. type MyHashMap struct {
    6. data []list.List
    7. }
    8. /** Initialize your data structure here. */
    9. func Constructor() MyHashMap {
    10. return MyHashMap{
    11. data: make([]list.List, buckets),
    12. }
    13. }
    14. func (this *MyHashMap) hash(key int) int {
    15. return key%buckets
    16. }
    17. /** value will always be non-negative. */
    18. func (this *MyHashMap) Put(key int, value int) {
    19. b := this.hash(key)
    20. for cur := this.data[b].Front(); cur != nil; cur = cur.Next() {
    21. if e := cur.Value.(*entry); e.key == key {
    22. e.val = value
    23. return
    24. }
    25. }
    26. this.data[b].PushBack(&entry{key: key, val: value})
    27. return
    28. }
    29. /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    30. func (this *MyHashMap) Get(key int) int {
    31. b := this.hash(key)
    32. for cur := this.data[b].Front(); cur != nil; cur = cur.Next() {
    33. if e := cur.Value.(*entry); e.key == key {
    34. return e.val
    35. }
    36. }
    37. return -1
    38. }
    39. /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    40. func (this *MyHashMap) Remove(key int) {
    41. b := this.hash(key)
    42. for cur := this.data[b].Front(); cur != nil; cur = cur.Next() {
    43. if e := cur.Value.(*entry); e.key == key {
    44. this.data[b].Remove(cur)
    45. return
    46. }
    47. }
    48. }
    49. /**
    50. * Your MyHashMap object will be instantiated and called as such:
    51. * obj := Constructor();
    52. * obj.Put(key,value);
    53. * param_2 := obj.Get(key);
    54. * obj.Remove(key);
    55. */