题解 | #设计LRU缓存结构#利用队列实现,简单
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
import java.util.*; public class Solution { /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ public int[] LRU (int[][] operators, int k) { ArrayList<Integer> res = new ArrayList<>(); LinkedList<Integer> stack = new LinkedList<>(); HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); for(int i=0;i<operators.length;i++){ int key = operators[i][1]; boolean exist = stack.contains(key); if(operators[i][0]==1){ hm.put(key, operators[i][2]); if( exist ){ //若在remove里不强转key对对象类型的话,则将key认为是对应下标的索引,最终会报索引超出异常 stack.remove((Integer)key); stack.addFirst(key); }else{ if(stack.size()>=k){ stack.removeLast(); } stack.addFirst(key); } }else if(operators[i][0]==2){ if( exist ){ //若在remove里不强转key对对象类型的话,则将key认为是对应下标的索引,最终会报索引超出异常 stack.remove((Integer)key); stack.addFirst(key); res.add(hm.get(key)); }else{ res.add(-1); } } } int[] r = new int[res.size()]; for(int i=0;i<res.size();i++){ r[i] = res.get(i); } return r; } }