Advertisement
Guest User

LRUCache

a guest
Sep 22nd, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. import java.util.Deque;
  2. import java.util.HashSet;
  3. import java.util.Iterator;
  4. import java.util.LinkedList;
  5.  
  6. public class LRUCache {
  7. // store keys of cache
  8. static Deque<Integer> dq;
  9. // store references of key in cache
  10. static HashSet<Integer> map;
  11. // maximum capacity of cache
  12. static int csize;
  13.  
  14. LRUCache(int n) {
  15. dq = new LinkedList<>();
  16. map = new HashSet<>();
  17. csize = n;
  18. }
  19.  
  20. /* Refers key x with in the LRU cache */
  21. public void refer(int x) {
  22. if (!map.contains(x)) {
  23. if (dq.size() == csize) {
  24. int last = dq.removeLast();
  25. map.remove(last);
  26. }
  27. } else {
  28. /* The found page may not be always the last element, even if it's an
  29. intermediate element that needs to be removed and added to the start
  30. of the Queue */
  31. int index = 0, i = 0;
  32. Iterator<Integer> itr = dq.iterator();
  33. while (itr.hasNext()) {
  34. if (itr.next() == x) {
  35. index = i;
  36. break;
  37. }
  38. i++;
  39. }
  40. dq.remove(index);
  41. }
  42. dq.push(x);
  43. map.add(x);
  44. }
  45.  
  46. // display contents of cache
  47. public void display() {
  48. Iterator<Integer> itr = dq.iterator();
  49. while (itr.hasNext()) {
  50. System.out.print(itr.next() + " ");
  51. }
  52. }
  53.  
  54. public static void main(String[] args) {
  55. LRUCache ca = new LRUCache(4);
  56. ca.refer(1);
  57. ca.refer(2);
  58. ca.refer(3);
  59. ca.refer(1);
  60. ca.refer(4);
  61. ca.refer(5);
  62. ca.display();
  63. }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement