LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

 

思路:用HashMap和双向链表来实现

参考:http://www.programcreek.com/2013/03/leetcode-lru-cache-java/

java代码:

  1. public class LRUCache {
  2. Map<Integer,LinkNode> mp = new HashMap<Integer,LinkNode>();
  3. int capacity;
  4. LinkNode head;
  5. LinkNode tail;
  6. int cur;
  7. public LRUCache(int capacity) {
  8. this.capacity = capacity;
  9. cur = 0;
  10. head = null;
  11. tail = null;
  12. }
  13. void moveToHead(LinkNode p) {
  14. p.next = head;
  15. p.pre = null;
  16. if(head!=null) {
  17. head.pre = p;
  18. }
  19. head = p;
  20. if(tail == null) {
  21. tail = p;
  22. }
  23. }
  24. void removeNode(LinkNode p) {
  25. LinkNode curNode = p;
  26. LinkNode preNode = p.pre;
  27. LinkNode nextNode = p.next;
  28. if(preNode!=null) {
  29. preNode.next = nextNode;
  30. } else {
  31. head = nextNode;
  32. }
  33. if(nextNode!=null) {
  34. nextNode.pre = preNode;
  35. } else {
  36. tail = preNode;
  37. }
  38. }
  39. public int get(int key) {
  40. if(mp.containsKey(key)) {
  41. LinkNode p = mp.get(key);
  42. removeNode(p);
  43. moveToHead(p);
  44. return p.value;
  45. } else {
  46. return -1;
  47. }
  48. }
  49. public void set(int key, int value) {
  50. if(mp.containsKey(key)) {
  51. LinkNode p = mp.get(key);
  52. removeNode(p);
  53. p.value = value;
  54. moveToHead(p);
  55. } else {
  56. LinkNode p = new LinkNode(key,value);
  57. if(cur==capacity) {
  58. mp.remove(tail.key);
  59. tail = tail.pre;
  60. if(tail!=null) tail.next = null;
  61. moveToHead(p);
  62. mp.put(key,p);
  63. } else {
  64. moveToHead(p);
  65. mp.put(key,p);
  66. cur++;
  67. }
  68. }
  69. }
  70. }
  71. class LinkNode{
  72. public int key;
  73. public int value;
  74. public LinkNode pre;
  75. public LinkNode next;
  76. public LinkNode(int key,int value) {
  77. this.key = key;
  78. this.value = value;
  79. pre = null;
  80. next = null;
  81. }
  82. }
posted @ 2014-07-25 10:41  purejade  阅读(102)  评论(0)    收藏  举报