题解 | #设计LRU缓存结构#

设计LRU缓存结构

http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public Map.Entry<Integer,Integer> getHead(LinkedHashMap map) {
        return (Map.Entry<Integer,Integer>)map.entrySet().iterator().next();
    }
    public int[] LRU (int[][] operators, int k) {
        // write code here
        LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        for(int i=0;i<operators.length;i++){
            if(operators[i][0]==1){
                if(map.containsKey(operators[i][1]))
                    map.remove(operators[i][1]);
                if(map.size()>=k)
                    map.remove(getHead(map).getKey());
                map.put(operators[i][1],operators[i][2]);
            }else{
                if(map.containsKey(operators[i][1])){
                    int value = map.get(operators[i][1]);
                    map.remove(operators[i][1]);
                    map.put(operators[i][1],value);
                    list.add(value);
                }else{
                    list.add(-1);
                }
           
            }
        }
        int []array = new int[list.size()];
        for(int i=0;i<array.length;i++){
            array[i] = list.get(i);
        }
        return array;
    }
}
全部评论

相关推荐

10-14 23:01
已编辑
中国地质大学(武汉) Java
CUG芝士圈:虽然是网上的项目,但最好还是包装一下,然后现在大部分公司都在忙校招,十月底、十一月初会好找一些。最后,boss才沟通100家,别焦虑,我去年暑假找第一段实习的时候沟通了500➕才有面试,校友加油
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务