We need to use the correct LinkedHashMap constructor with correct arguments to make sure it behaves as LRU cache. Below is the doc from JDK:
"A special
constructor
is
provided to create a linked hash map whose order of iteration is the order
in which its entries were last accessed, from least-recently accessed to
most-recently (access-order). "And here is the code which passed the LeetCode tests and beat 90% Java implementation in terms of the runtime.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LRUCache { | |
LinkedHashMap<Integer, Integer> cache; | |
public LRUCache(int capacity){ | |
cache = new LinkedHashMap<Integer, Integer>(capacity, (float) 0.75, true){ | |
@Override | |
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest){ | |
return this.size() > capacity; | |
} | |
}; | |
} | |
public List<Integer> getValuesAsList(){ | |
return new ArrayList<>(cache.values()); | |
} | |
public int get(int key) { | |
Integer result = cache.get(key); | |
if(result==null) | |
result = -1; | |
return result; | |
} | |
public void set(int key, int value) { | |
cache.put(key, value); | |
} | |
} |
No comments:
Post a Comment