题解 | #设计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;
    }
}


全部评论

相关推荐

nbdy:字太多了,写简历不是写自传,亮点难点技能点列出来就行,要简明扼要
点赞 评论 收藏
分享
28小凳也想实习:项目不用一个业务一个轮子吗,刷牛客好多人说要一业务一轮子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务