PHP

  1. class LRUCache {
  2. private $capacity;
  3. private $map;
  4. /**
  5. * @param Integer $capacity
  6. */
  7. function __construct($capacity) {
  8. $this->capacity = $capacity;
  9. }
  10. /**
  11. * @param Integer $key
  12. * @return Integer
  13. */
  14. function get($key) {
  15. $key = 'k_' . $key;
  16. if (isset($this->map[$key])) {
  17. $val = $this->map[$key];
  18. unset($this->map[$key]);
  19. $this->map[$key] = $val;
  20. return $val;
  21. } else {
  22. return -1;
  23. }
  24. }
  25. /**
  26. * @param Integer $key
  27. * @param Integer $value
  28. * @return NULL
  29. */
  30. function put($key, $value) {
  31. $key = 'k_' . $key;
  32. if (isset($this->map[$key])) {
  33. unset($this->map[$key]);
  34. $this->map[$key] = $value;
  35. return;
  36. }
  37. if (count($this->map) >= $this->capacity) {
  38. array_shift($this->map);
  39. }
  40. $this->map[$key] = $value;
  41. }
  42. }
  43. /**
  44. * $obj = LRUCache($capacity);
  45. * $ret_1 = $obj->get($key);
  46. * $obj->put($key, $value);
  47. */

Go

  1. type LRUCache struct {
  2. capacity int
  3. m map[int]*Node
  4. head, tail *Node
  5. }
  6. type Node struct {
  7. Key int
  8. Value int
  9. Pre, Next *Node
  10. }
  11. func (this *LRUCache) Get(key int) int {
  12. if v, ok := this.m[key]; ok {
  13. this.moveToHead(v)
  14. return v.Value
  15. }
  16. return -1
  17. }
  18. func (this *LRUCache) moveToHead(node *Node) {
  19. this.deleteNode(node)
  20. this.addToHead(node)
  21. }
  22. func (this *LRUCache) deleteNode(node *Node) {
  23. node.Pre.Next = node.Next
  24. node.Next.Pre = node.Pre
  25. }
  26. func (this *LRUCache) removeTail() int {
  27. node := this.tail.Pre
  28. this.deleteNode(node)
  29. return node.Key
  30. }
  31. func (this *LRUCache) addToHead(node *Node) {
  32. this.head.Next.Pre = node
  33. node.Next = this.head.Next
  34. node.Pre = this.head
  35. this.head.Next = node
  36. }
  37. func (this *LRUCache) Put(key int, value int) {
  38. if v, ok := this.m[key]; ok {
  39. v.Value = value
  40. this.moveToHead(v)
  41. return
  42. }
  43. if this.capacity == len(this.m) {
  44. rmKey := this.removeTail()
  45. delete(this.m, rmKey)
  46. }
  47. newNode := &Node{Key: key, Value: value}
  48. this.addToHead(newNode)
  49. this.m[key] = newNode
  50. }
  51. func Constructor(capacity int) LRUCache {
  52. head, tail := &Node{}, &Node{}
  53. head.Next = tail
  54. tail.Pre = head
  55. return LRUCache{
  56. capacity: capacity,
  57. m: map[int]*Node{},
  58. head: head,
  59. tail: tail,
  60. }
  61. }