首页 > 其他 > 详细

设计题

时间:2021-01-27 14:41:34      阅读:31      评论:0      收藏:0      [点我收藏+]

1.  LRU 缓存机制

 运用你所掌握的数据结构,设计和实现一个  LRU (最近最少使用) 缓存机制

实现 LRUCache 类:

  • LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
  • int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1
  • void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。

 

进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?

 

解题思路: 参考LinkedHashMap的实现方式。 HashMap + 双向链表。

 

public class LRUCache {
    private HashMap<Integer, Entry> cache;
    private Entry head;
    private Entry tail;
    private int capacity;
    private int size;

    public LRUCache(int capacity) {
        cache = new HashMap<>();
        this.capacity = capacity;
        size = 0;
    }

    public int get(int key) {
        if(!cache.containsKey(key)) {
            return -1;
        }
        Entry e = cache.get(key);
        afterAccess(e);
        return e.value;
    }


    public void put(int key, int value) {
        if(!cache.containsKey(key)) {
            Entry e = new Entry(key,value);
            cache.put(key,e);
            afterInsertion(e);
            size++;
        } else {
            Entry e = cache.get(key);
            e.value = value;
            cache.put(key, e);
            afterAccess(e);
        }

        if(size > capacity) {
            cache.remove(head.key);
            removeHead();
        }

    }

    private void removeHead() {
        Entry e = head.next;
        e.pre = null;
        head = e;
        size--;
    }

    private void afterAccess(Entry e) {
        Entry before = e.pre;
        Entry after = e.next;

        if(before == null) {
            Entry next = head.next;
            if(next == null) {
                return;
            }
            head = next;
            next.pre = null;
            tail.next = e;
            e.pre = tail;
            tail = e;
        } else if( e == tail) {
            return;
        } else {

            before.next = after;
            after.pre = before;

            tail.next = e;
            e.pre = tail;
            tail = e;
        }
    }

    private void afterInsertion(Entry e) {
        if(head == null) {
            head = e;
        } else {
            tail.next = e;
            e.pre = tail;
        }
        tail = e;
    }

    private static class Entry {
        int key;
        int value;
        Entry pre;
        Entry next;

        public Entry(){}
        public Entry(int key, int val) {
            this.key = key;
            this.value = val;
        }
    }
}

设计题

原文:https://www.cnblogs.com/billyqiu/p/14334557.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!