LFU Cache(LFU缓存)

问题

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 cache.

Have you met this question in a real interview? Yes
Example
Given capacity=3

LFU Cache(LFU缓存)_第1张图片

分析

需要注意是除了要求访问次数排序之外,如果访问次数相同,还需要按照时间排序,最后访问的最后删除。

代码

public class LFUCache {
    private List nodeList = new ArrayList<>();
    private int max = 0;
    private int frequency = 0;

    /*
    * @param capacity: An integer
    */
    public LFUCache(int capacity) {
        // do intialization if necessary
        max = capacity;
    }

    /*
     * @param key: An integer
     * @param value: An integer
     * @return: nothing
     */
    public void set(int key, int value) {
        // write your code here
        Node node = getNode(key);
        if (node == null) {
            node = new Node(key, value, 1, frequency);
            if (nodeList.size() >= max) {
                Collections.sort(nodeList);
                nodeList.remove(0);
            }
            nodeList.add(node);
        } else {
            node.value = value;
            node.times = node.times + 1;
            node.frequency = frequency;
        }
        frequency++;
    }


    private Node getNode(int key) {
        Node node = new Node(key);
        int i = nodeList.indexOf(node);
        if (i >= 0) {
            return nodeList.get(i);
        }
        return null;
    }

    /*
     * @param key: An integer
     * @return: An integer
     */
    public int get(int key) {
        // write your code here
        Node node = getNode(key);
        if (node != null) {
            node.times = node.times + 1;
            node.frequency = frequency;
            frequency++;
            return node.value;
        }
        return -1;
    }

    private class Node implements Comparable {
        int key;
        int value;
        int times;
        int frequency;

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

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Node node = (Node) o;

            return key == node.key;

        }

        public Node(int key, int value, int times, int frequency) {
            this.key = key;
            this.value = value;
            this.times = times;
            this.frequency = frequency;
        }

        @Override
        public int compareTo(Node node) {
            if (times > node.times) {
                return 1;
            } else if (times < node.times) {
                return -1;
            } else {
                return frequency > node.frequency ? 1 : -1;
            }
        }
    }
}

你可能感兴趣的:(LFU Cache(LFU缓存))