1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class LRUCache { int capacity = 0; LinkedList queue = new LinkedList<Integer>(); Map<Integer, Integer> map = new HashMap<>(); public LRUCache(int capacity) { this.capacity = capacity; } public int get(int key) { if(!map.containsKey(key)){ return -1; } queue.remove((Integer) key); queue.offerFirst(key); return map.get(key); } public void put(int key, int value) { if(map.containsKey(key)){ queue.remove((Integer) key); queue.offerFirst(key); map.put(key, value); return; }
if(queue.size() == capacity){ map.remove(queue.peekLast()); queue.removeLast(); } queue.offerFirst(key); map.put(key, value); } }
|