LRU Cache

Question

Problem Statement

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.

题解

Java

  1. public class Solution {
  2. private int capacity;
  3. private HashMap<Integer, Node> map = new HashMap<>();
  4. private Node head = new Node(-1, -1), tail = new Node(-1, -1);
  5. private class Node {
  6. Node prev, next;
  7. int val, key;
  8. public Node(int key, int val) {
  9. this.val = val;
  10. this.key = key;
  11. prev = null;
  12. next = null;
  13. }
  14. // @Override
  15. // public String toString() {
  16. // return "(" + key + ", " + val + ") " + "last:"
  17. // + (prev == null ? "null" : "node");
  18. // }
  19. }
  20. public Solution(int capacity) {
  21. this.capacity = capacity;
  22. tail.prev = head;
  23. head.next = tail;
  24. }
  25. public int get(int key) {
  26. if (!map.containsKey(key)) {
  27. return -1;
  28. }
  29. // remove current
  30. Node currentNode = map.get(key);
  31. currentNode.prev.next = currentNode.next;
  32. currentNode.next.prev = currentNode.prev;
  33. // move current to tail;
  34. moveToTail(currentNode);
  35. return map.get(key).val;
  36. }
  37. public void set(int key, int value) {
  38. if (get(key) != -1) {
  39. map.get(key).val = value;
  40. return;
  41. }
  42. if (map.size() == capacity) {
  43. map.remove(head.next.key);
  44. head.next = head.next.next;
  45. head.next.prev = head;
  46. }
  47. Node insert = new Node(key, value);
  48. map.put(key, insert);
  49. moveToTail(insert);
  50. }
  51. private void moveToTail(Node current) {
  52. current.prev = tail.prev;
  53. tail.prev = current;
  54. current.prev.next = current;
  55. current.next = tail;
  56. }
  57. }