最近在leetcode上做题的时,看到了一道有关LRU Cache的题目,正好我当初面试阿里巴巴的时候问到的。主要采用linkedHashMap来实现。
package edu.test.algorithm;import java.util.LinkedHashMap;public class LRUCache { LinkedHashMaplinkedHashMap; int capacity; public LRUCache(int capacity) { linkedHashMap=new LinkedHashMap (capacity); this.capacity=capacity; } public int get(int key) { if(linkedHashMap.containsKey(key)){ int value=linkedHashMap.get(key); linkedHashMap.remove(key); linkedHashMap.put(key, value); return value; } return -1; } public void set(int key, int value) { if(linkedHashMap.containsKey(key)){ linkedHashMap.remove(key); } else if(linkedHashMap.size()>=capacity){ linkedHashMap.remove(linkedHashMap.keySet().iterator().next()); } linkedHashMap.put(key, value); } }