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

设计LRU缓存结构

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

优先队列

提供另一种思路解决问题,不能算最优解吧,能过此题。

  • 优先队列:设置一个标志位用来表示最近处理情况。优先队列的排序就以次标志位,升序、小顶堆,对顶就是最久未使用元素。
  • 设一个全局变量recent。每次添加元素的时候,recent++。这样做有个问题++到上限之后怎么办。但题目的数据量不过几千无需考虑次问题。
  • 再用一个HashMap快速检索 使用存在要查询的元素。
  • PriorityQueue的remove(o), 是删除o.equal()的元素。时间复杂度 O(n)


public class Solution {
    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
		int recent = 0;
		PriorityQueue<Node> que = new PriorityQueue<Node>((o1, o2) -> o1.re - o2.re);
		HashMap<Integer, Integer> map = new HashMap<>();
		ArrayList<Integer> list = new ArrayList<>();
		for (int[] operator : operators) {
			if (operator[0] == 1) {
				if (que.size() < k) {
					map.put(operator[1], operator[2]);
					que.add(new Node(recent++, operator[1], operator[2]));
				} else {
					Node poll = que.poll();
					que.add(new Node(recent++, operator[1], operator[2]));
					map.remove(poll.key);
					map.put(operator[1], operator[2]);
				}
			} else {
				if (map.containsKey(operator[1])) {
					int val = map.get(operator[1]);
					que.remove(new Node(operator[1]));
					list.add(val);
					que.add(new Node(recent++, operator[1], val));
				} else {
					list.add(-1);
				}
			}

		}
		int ans[] = new int[list.size()];
		int len = list.size();
		for (int i = 0; i < len; i++) {
			ans[i] = list.get(i);
		}
		return ans;
	}
    class Node  {
         int re;
         int key;
         int val;

        public Node(int re, int key, int val) {
            this.re = re;
            this.key = key;
            this.val = val;
        }

        public Node(int key) {
            this.key = key;
        }

        @Override
        public boolean equals(Object obj) {
        	//用于删除 key 相同的元素
            Node a = (Node) obj;
            return key == a.key;
        }
    }
}
全部评论

相关推荐

莫忧莫惧莫回头:md,诈骗犯!之前的简历都是男的。现在想改成女的让我们给你建议是吧😅。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务