146.lru-cache.go 1.7 KB

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