8.12 [LeetCode] 146 LRU Cache

Question

link

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.

Stats

Adjusted Difficulty 4
Time to use Very difficult

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a difficult question, I can’t write the solution easily even after a month.

Solution

The solution is to use a Doubly-linked-list and a HashMap. Doing this allows O(1) search, remove and insert. A very nice and sophisticated data structure example, and very high frequency in interviews.

2 important things to note while coding:

  1. We need 2 helper methods: removeNode() and setNodeAsHead().

    Because we reuse both methods for get() and set() methods.

  2. Initialization of LRU

    We need 5 variables: capacity, current size(optional but good to have), hashmap, head, tail. Don‘t forget initialize tail.

  3. Initialization of DoubleLinkedListNode (the key in List is the same as the key in map so we can reference from each other)

    This is easy, but do not forget about both key and value variable. We must use DoubleLinkedListNode.key when we want to delete tail.

Code

public class LRUCache {
    int size, capacity;
    HashMap<Integer, DoubleLink> map = new HashMap<Integer, DoubleLink>();
    DoubleLink head;
    DoubleLink tail;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        this.head = null;
        this.tail = null;
    }

    public void remove(DoubleLink node) {
        if(node == head && node == tail) {
            head = null;
            tail = null;
        }else if(node == tail) {
            tail.prev.next = null;
            tail = tail.prev;
        }else{
            node.prev.next = node.next;
            node.next.prev = node.prev;
        }
        node.prev = null;
        node.next = null;
    }

    public void setHead(DoubleLink node) {
        if(head != null) {
            head.prev = node;
            node.next = head;
            node.prev = null;
            head = node;
        }else { // first node inserted
            head = node;
            tail = node;
        }
    }

    public int get(int key) {
        if(! map.containsKey(key)) // key not found
            return -1;
        DoubleLink target = map.get(key);
        if(target != head) { // if it is already head we do not need to update it.
            remove(target);
            setHead(target);
        }
        return map.get(key).val;
    }

    public void set(int key, int value) {
        if(get(key) != -1) { // update old node
            DoubleLink node = map.get(key);
            node.val = value;
            if(node != head) {
                remove(node);
                setHead(node);
            }
        } else { // insert new node
            DoubleLink newHead = new DoubleLink(key, value);
            if(size == capacity) {
                map.remove(tail.key);
                remove(tail);
            }
            else
                size++;
            map.put(key, newHead);
            setHead(newHead);
        }
    }
    class DoubleLink { // DoubleLinkedList can delete a node moer easily cause you can use node.prev to connect node.next.
        int val;
        int key;
        DoubleLink next;
        DoubleLink prev;
        public DoubleLink(int k, int v) {
            this.key = k;
            this.val = v;
        }
    }
}
时间: 2024-12-20 01:07:02

8.12 [LeetCode] 146 LRU Cache的相关文章

Java for LeetCode 146 LRU Cache 【HARD】

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

[leetcode]146. LRU Cache

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(

LeetCode 之 LRU Cache Java实现

LeetCode刷了41道题了,流程是按照戴兄的小书,很多不会的是参考Kim姐的代码,自己用Java抠腚的. 前几天做到了LRU Cache: C++的实现方法大同小异,大都用的是一个list加一个hash,hash中存储list节点地址,每次get从hash中寻key,有则将list相应节点放到链表头,没有则返回-1:每次set先判断hash中是否存在,存在则将相应节点移到表头,重置value值,如果不存在,判定长度是否达到预设的capacity,如果达到,删除表尾节点,新节点插入表头. 但是

由LeetCode的LRU Cache谈到操作系统中LRU算法

1 class LRUCache{ 2 public: 3 LRUCache(int capacity) { 4 size = capacity; 5 } 6 int get(int key) { 7 if(cacheMap.find(key)==cacheMap.end()) 8 return -1; 9 cacheList.splice(cacheList.begin(),cacheList,cacheMap[key]); 10 cacheMap[key] = cacheList.begin

No.146 LRU Cache

No.146 LRU Cache 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, otherwi

【LeetCode】LRU Cache

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

LeetCode OJ - LRU Cache

题目: 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.

146. LRU Cache(js)

146. LRU Cache Design and implement a data structure for Least Recently Used (LRU) 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

LeetCode:LRU cache

题目:LRU cache 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 r