LeetCode 题解(85): LRU Cache

来源:互联网 发布:淘宝好评能改差评吗 编辑:程序博客网 时间:2024/05/18 03:13

题目:

Design and implement a data structure for Least Recently Used (LRU) 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.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

题解:

使用HashMap保存key到链表节点的映射,这样在删除节点时只需O(1)查找时间。

c++版:

class LRUCache{public:    LRUCache(int capacity) {        cacheCapacity = capacity;    }        int get(int key) {        if(cache.find(key) == cache.end())            return -1;        auto temp = cache[key];        LRUtable.erase(cache[key]);        LRUtable.push_front(*temp);        cache[key] = LRUtable.begin();        return cache[key]->second;    }        void set(int key, int value) {        if(cache.find(key) != cache.end()) {            cache[key]->second = value;            auto temp = cache[key];            LRUtable.erase(cache[key]);            LRUtable.push_front(*temp);            cache[key] = LRUtable.begin();        } else {            if(cacheCapacity == cache.size()) {                cache.erase(LRUtable.back().first);                LRUtable.pop_back();                LRUtable.push_front(pair<int, int>(key, value));                cache[key] = LRUtable.begin();            } else {                LRUtable.push_front(pair<int, int>(key, value));                cache[key] = LRUtable.begin();            }        }    }private:    int cacheCapacity = 0;    unordered_map<int, list<pair<int, int>>::iterator> cache;    list<pair<int, int>> LRUtable;};

Java版:

public class LRUCache {    public LRUCache(int capacity) {        cacheCapacity = capacity;        cache = new HashMap<>();        head = null;        tail = null;    }        public int get(int key) {        if(!cache.containsKey(key))            return -1;        Node current = cache.get(key);        moveNodeAhead(current);        cache.put(key, head);        return cache.get(key).value;    }        public void set(int key, int value) {        if(cache.containsKey(key)) {            Node current = cache.get(key);            current.value = value;            moveNodeAhead(current);            cache.put(key, head);        } else {            if(cacheCapacity == cache.size()) {                cache.remove(tail.key);                if(tail == head) {                    head.key = key;                    head.value = value;                } else {                    tail = tail.prev;                    tail.next = null;                    Node current = new Node(key, value);                    current.next = head;                    head.prev = current;                    head = current;                }                cache.put(key, head);            } else {                if(head == null) {                    head = new Node(key, value);                    tail = head;                    cache.put(key, head);                } else {                    Node current = new Node(key, value);                    current.next = head;                    head.prev = current;                    head = current;                    cache.put(key, head);                }            }        }    }        void moveNodeAhead(Node current) {        if(current != head && current != tail) {            current.prev.next = current.next;            current.next.prev = current.prev;        } else if(current != head && current == tail) {            tail = current.prev;            current.prev.next = null;        }                if(current != head) {            current.next = head;            head.prev = current;            head = current;        }    }        private class Node {        int key;        int value;        Node prev;        Node next;        Node() {            key = 0;            value = 0;            prev = null;            next = null;        }        Node(int k, int v) {            key = k;            value = v;            prev = null;            next = null;        }    }    private int cacheCapacity = 0;    private HashMap<Integer, Node> cache;    private Node head;    private Node tail;}

Python版:

class LRUCache:    class Node:        def __init__(self, k, v):            self.key = k            self.value = v            self.prev_node = None            self.next_node = None    # @param capacity, an integer    def __init__(self, capacity):        self.cache_capacity = capacity        self.cache = {}        self.head = None        self.tail = None    # @return an integer    def get(self, key):        if key in self.cache.keys():            current = self.cache[key]            self.moveAhead(current)            self.cache[key] = self.head            return current.value        else:            return -1    # @param key, an integer    # @param value, an integer    # @return nothing    def set(self, key, value):        if key in self.cache.keys():            current = self.cache[key]            current.value = value            self.moveAhead(current)            self.cache[key] = self.head        else:            if self.cache_capacity == len(self.cache):                self.cache.pop(self.tail.key)                if self.head == self.tail:                    self.head.key = key                    self.tail.value = value                else:                    self.tail = self.tail.prev_node                    self.tail.next_node = None                    current = self.Node(key, value)                    current.next_node = self.head                    self.head.prev_node = current                    self.head = current                self.cache[key] = self.head            else:                if self.head == None:                    self.head = self.Node(key, value)                    self.tail = self.head                else:                    current = self.Node(key, value)                    current.next_node = self.head                    self.head.prev_node = current                    self.head = current                self.cache[key] = self.head    def moveAhead(self, current):        if current != self.head and current != self.tail:            current.next_node.prev_node = current.prev_node            current.prev_node.next_node = current.next_node        elif current != self.head and current == self.tail:            self.tail = current.prev_node            current.prev_node.next_node = None        if current != self.head:            current.next_node = self.head            self.head.prev_node = current            self.head = current        return

0 0
原创粉丝点击