image.png

思路

使用内置LinkedHashMap

image.png

  1. class LRUCache extends LinkedHashMap<Integer,Integer>{
  2. private int capacity;
  3. public LRUCache(int capacity){
  4. super(capacity,0.75f,true);
  5. this.capacity=capacity;
  6. }
  7. public int get(int key){
  8. return super.getOrDefault(key,-1);
  9. }
  10. public void put(int key,int value){
  11. super.put(key, value);
  12. }
  13. @Override
  14. protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
  15. return size() > capacity;
  16. }
  17. }