LRU cache (basic)
Java
Hard
4 views
Problem Description
Task: implement a small LRU cache using LinkedHashMap. Support get/put with capacity.
Output Format
Return value
Constraints
Use accessOrder=true.
Official Solution
static class LRU{private final int cap;private final java.util.LinkedHashMap<Integer,Integer> m;LRU(int c){cap=c;m=new java.util.LinkedHashMap<>(16,0.75f,true){protected boolean removeEldestEntry(java.util.Map.Entry<Integer,Integer> e){return size()>cap;}};}int get(int k){return m.getOrDefault(k,-1);}void put(int k,int v){m.put(k,v);}}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!