lfu-cache(需要O(1),所以挺难的)

https://leetcode.com/problems/lfu-cache/

很难,看了下面的参考:

https://discuss.leetcode.com/topic/69137/java-o-1-accept-solution-using-hashmap-doublelinkedlist-and-linkedhashset

注意其中的思想就是如下所述:

Your idea is brilliant... Especially storing all keys with same counts in one node, 

if one of the keys in that node got hit once more, it will be moved into a new node with (count+1) if the node exits or it will be wrapped into a newly created node with (count+1).
All your operations are guaranteed O(1) no doubt.

There is no way to complete it bug-free within half an hour. So in the real interview, I might as well explain the idea and how we should implement all operations in each scenario, instead of actually trying to complete whole program...Anyway, thank you so much for your time and explanation. 

并且注意,用到了LinkedHashSet的特性,就是虽然是Set,但是是按照顺序插入的方式来遍历的。

public class LFUCache {
    private Node head = null;
    private int cap = 0;
    private HashMap<Integer, Integer> valueHash = null;
    private HashMap<Integer, Node> nodeHash = null;

    public LFUCache(int capacity) {
        this.cap = capacity;
        valueHash = new HashMap<Integer, Integer>();
        nodeHash = new HashMap<Integer, Node>();
    }

    public int get(int key) {
        if (valueHash.containsKey(key)) {
            increaseCount(key);
            return valueHash.get(key);
        }
        return -1;
    }

    public void set(int key, int value) {
        if ( cap == 0 ) return;
        if (valueHash.containsKey(key)) {
            valueHash.put(key, value);
            Node node = nodeHash.get(key);
            node.keys.remove(key);
            node.keys.add(key);
        } else {
            if (valueHash.size() < cap) {
                valueHash.put(key, value);
            } else {
                removeOld();
                valueHash.put(key, value);
            }
            addToHead(key);
        }
        increaseCount(key);
    }

    private void addToHead(int key) {
        if (head == null) {
            head = new Node(0);
            head.keys.add(key);
        } else if (head.count > 0) {
            Node node = new Node(0);
            node.keys.add(key);
            node.next = head;
            head.prev = node;
            head = node;
        } else {
            head.keys.add(key);
        }
        nodeHash.put(key, head);
    }

    private void increaseCount(int key) {
        Node node = nodeHash.get(key);
        node.keys.remove(key);

        if (node.next == null) {
            node.next = new Node(node.count+1);
            node.next.prev = node;
            node.next.keys.add(key);
        } else if (node.next.count == node.count+1) {
            node.next.keys.add(key);
        } else {
            Node tmp = new Node(node.count+1);
            tmp.keys.add(key);
            tmp.prev = node;
            tmp.next = node.next;
            node.next.prev = tmp;
            node.next = tmp;
        }

        nodeHash.put(key, node.next);
        if (node.keys.size() == 0) remove(node);
    }

    private void removeOld() {
        if (head == null) return;
        int old = 0;
        for (int n: head.keys) {
            old = n;
            break;
        }
        head.keys.remove(old);
        if (head.keys.size() == 0) remove(head);
        nodeHash.remove(old);
        valueHash.remove(old);
    }

    private void remove(Node node) {
        if (node.prev == null) {
            head = node.next;
        } else {
            node.prev.next = node.next;
        }
        if (node.next != null) {
            node.next.prev = node.prev;
        }
    }

    class Node {
        public int count = 0;
        public LinkedHashSet<Integer> keys = null;
        public Node prev = null, next = null;

        public Node(int count) {
            this.count = count;
            keys = new LinkedHashSet<Integer>();
            prev = next = null;
        }
    }
}
/**
 * Your LFUCache object will be instantiated and called as such:
 * LFUCache obj = new LFUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.set(key,value);
 */
时间: 2024-10-08 21:33:37

lfu-cache(需要O(1),所以挺难的)的相关文章

460. LFU Cache

460. LFU Cache Total Accepted: 5305 Total Submissions: 26292 Difficulty: Hard Contributors: 1337c0d3r, fishercoder Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: getand put. ge

[LeetCode] LFU Cache 最近最不常用页面置换缓存器

Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.pu

Leetcode: LFU Cache &amp;&amp; Summary of various Sets: HashSet, TreeSet, LinkedHashSet

Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and set. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. s

Lintcode24 LFU Cache solution 题解

[题目描述] LFU (Least Frequently Used) is a famous cache eviction algorithm.For a cache with capacity k, if the cache is full and need to evict a key in it, the key with the lease frequently used will be kicked out.Implement set and get method for LFU ca

[LeetCode] 460. LFU Cache 最近最不常用页面置换缓存器

Design and implement a data structure for Least Frequently Used (LFU) cache. It should support the following operations: get and put. get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.pu

LeetCode &quot;460. LFU Cache&quot; !

My first try was very close to a final solution .. however, this is a much neater solution: https://discuss.leetcode.com/topic/69436/concise-c-o-1-solution-using-3-hash-maps-with-explanation Lesson learnt: data structure is crucial. And, if some logi

lfu cache

void splice (iterator position, list& x, iterator i);  //将列表x中迭代器 i 指向的元素移到当前list的position指向的位置处,由于i指向的元素从列表x中被移除,所以迭代器 i 此时是invalid的:position是当前列表的迭代器,i是列表x的迭代器 class LRUCache{ public: LRUCache(int capacity) { cap = capacity; } int get(int key) { au

比&quot;考试&quot;难的&quot;考试&quot;

打上学以后,就开始面对各种各样的考试. "考试",对于我来说,挺难的,考试整体下来就这么一个流程,考前准备,考试中奋笔疾书,考试完心情好几天或者郁闷几天.考试匆匆结束,结束了的结果就是过了或者挂了. 但是这种为人家准备"考试"的工作,还是第一次实践.这几天参与考试系统维护,不仅是目睹整个过程,更是真真切切的参与了,这种心情,只有参与的人才明白其中的喜怒哀乐. 考前:考试系统,大家都不是很了解,我们算是使用它的"顾客"吧,这之中的感受,想必只有我们

guava之cache

转自:http://ifeve.com/google-guava-cachesexplained/ 范例 01 LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() 02         .maximumSize(1000) 03         .expireAfterWrite(10, TimeUnit.MINUTES) 04         .removalListener(MY_LISTENER) 05