题解 | #java使用map解题#

设计LRU缓存结构

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

使用HashMap轻松解决设计LRU缓存结构

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) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        HashMap<Integer, int[]> map = new HashMap<>(); // int[] 是一个长度为二的数组,第一位用来记录value 第二位用来记录权值 权值越小 越不经常使用
        int count = 0; // 权值

        for (int[] operator : operators) {
            if (operator[0] == 1) {
                int min = Integer.MAX_VALUE;
                int minKey = 0;
                if (map.size() == k) {
                    for (Map.Entry<Integer, int[]> entry : map.entrySet()) {
                        if (entry.getValue()[1] < min) {
                            min = entry.getValue()[1];
                            minKey = entry.getKey(); 
                        }
                    }
                    map.remove(minKey);
                }
                map.put(operator[1],new int[]{operator[2], count++});
            } else {
                if (map.containsKey(operator[1])) {
                    list.add(map.get(operator[1])[0]);
                    map.get(operator[1])[1] = count++;
                } else {
                    list.add(-1);
                }
            }
        }

        int[] res = new int[list.size()];

        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }

        return res;
    }
}

想了想其实很多东西都用到了缓存,java开发中最常用的就是redis,
由于内存是有限的,不得不需要算法去取舍数据,要是内存无限大,那不起飞? 也没有这么多奇奇怪怪的算法了哈哈哈

全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务