面试题 16.25. LRU缓存

image.png

  1. package main
  2. import (
  3. "container/list"
  4. "fmt"
  5. )
  6. type Node struct {
  7. key int
  8. value int
  9. }
  10. type LRUCache struct {
  11. m map[int] *list.Element
  12. l *list.List
  13. capacity int
  14. }
  15. func Constructor(capacity int) LRUCache {
  16. return LRUCache{
  17. m: make(map[int]*list.Element),
  18. l: list.New(),
  19. capacity: capacity,
  20. }
  21. }
  22. func (this *LRUCache) Get(key int) int {
  23. if v,ok:=this.m[key];ok {
  24. this.l.MoveToFront(v)
  25. r := v.Value.(*Node)
  26. return r.value
  27. }
  28. return -1
  29. }
  30. func (this *LRUCache) Put(key int, value int) {
  31. if v,ok:=this.m[key];ok {
  32. n := v.Value.(*Node)
  33. n.value = value
  34. this.l.MoveToFront(v)
  35. }else {
  36. if this.capacity==len(this.m) {
  37. node := this.l.Back()
  38. n := node.Value.(*Node)
  39. delete(this.m,n.key)
  40. this.l.Remove(node)
  41. }
  42. n :=&Node{
  43. key: key,
  44. value: value,
  45. }
  46. e := this.l.PushFront(n)
  47. this.m[key] = e
  48. }
  49. }
  50. func main() {
  51. c := Constructor(2)
  52. p :=&c
  53. p.Put(2,1)
  54. p.Put(2,2)
  55. fmt.Println(p.Get(2))
  56. p.Put(1,1)
  57. p.Put(4,1)
  58. fmt.Println(p.Get(2))
  59. }

image.png