146.lru-cache.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. type listNode struct {
  2. key int
  3. val int
  4. prev *listNode
  5. next *listNode
  6. }
  7. type linkedList struct {
  8. head *listNode
  9. tail *listNode
  10. }
  11. func newLinkedList() *linkedList {
  12. head, tail := &listNode{}, &listNode{}
  13. head.next = tail
  14. tail.prev = head
  15. li := &linkedList{head, tail}
  16. return li
  17. }
  18. func (li *linkedList) remove(node *listNode) {
  19. node.prev.next = node.next
  20. node.next.prev = node.prev
  21. }
  22. func (li *linkedList) insert(node *listNode) {
  23. node.next = li.head.next
  24. node.prev = li.head
  25. li.head.next = node
  26. node.next.prev = node
  27. }
  28. type LRUCache struct {
  29. capacity int
  30. size int
  31. cache map[int]*listNode
  32. list *linkedList
  33. }
  34. func Constructor(capacity int) LRUCache {
  35. var lru LRUCache
  36. lru.capacity = capacity
  37. lru.cache = make(map[int]*listNode)
  38. lru.list = newLinkedList()
  39. return lru
  40. }
  41. func (this *LRUCache) Get(key int) int {
  42. if node, ok := this.cache[key]; ok {
  43. this.list.remove(node)
  44. this.list.insert(node)
  45. return node.val
  46. }
  47. return -1
  48. }
  49. func (this *LRUCache) Put(key int, value int) {
  50. if this.capacity == 0 {
  51. return
  52. }
  53. if node, ok := this.cache[key]; ok {
  54. this.list.remove(node)
  55. this.list.insert(node)
  56. node.val = value
  57. return
  58. }
  59. if this.size == this.capacity {
  60. node := this.list.tail.prev
  61. delete(this.cache, node.key)
  62. this.list.remove(node)
  63. this.size--
  64. }
  65. newNode := &listNode{key, value, nil, nil}
  66. this.list.insert(newNode)
  67. this.cache[key] = newNode
  68. this.size++
  69. }
  70. /**
  71. * Your LRUCache object will be instantiated and called as such:
  72. * obj := Constructor(capacity);
  73. * param_1 := obj.Get(key);
  74. * obj.Put(key,value);
  75. */