标签:style blog color java sp div on log bs
最近在leetcode上做题的时,看到了一道有关LRU Cache的题目,正好我当初面试阿里巴巴的时候问到的。主要采用linkedHashMap来实现。
package edu.test.algorithm; import java.util.LinkedHashMap; public class LRUCache { LinkedHashMap<Integer,Integer> linkedHashMap; int capacity; public LRUCache(int capacity) { linkedHashMap=new LinkedHashMap<Integer, Integer>(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); } }
标签:style blog color java sp div on log bs
原文地址:http://www.cnblogs.com/big-sun/p/4048261.html