146. LRU Cache

146. LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cachearrow-up-right. 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. put(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.

Follow up: Could you do both operations in O(1) time complexity?

Example:

LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

My Solutions:

  • 要求get和put都是O(1)的时间复杂度, 那么必须要用一个hashmap

  • 光用hashmap无法支持least recently used。如果想要知道某个元素使用的时间顺序,需要有一个list, 每次使用(get/put)的时候把这个元素放到list的最前面。 如果容量到了需要剔除的时候,直接把list的最后一个元素删除

  • 如何保证把list里面的某个元素换到最前面的时候也是O(1)操作呢?

    • 用arraylist肯定不可以, 因为把某一个元素放到最前面以后,还需要把后面的元素全部移动一遍,复杂度最差可能是O(N)

    • 用linkedlist是否可以? linkedlist删除中间的元素时候,有没有办法直接把前后的元素连起来就可以了? 这里想到如果每个node有prev,next, 那就可以这样操作了。所以其实这里只要实现一个doubly linked list, 然后在加上前面的那个map, 每次来一个key的时候,可以直接定位到这个node, 然后每个node有prev和next,那就可以用O(1)的时间移动位置,然后就可以完成get和put操作

有几个地方需要注意:

  • 在get一个node之后,需要把node从现在的位置删去,然后放在最前面。

  • 在put的时候检查需要是不是已经存在了有同样key的node。

    • 如果已经有了同样key的node,更新ta的value。同样的把node从现在的位置删去,然后放在最前面。

    • 如果没有同样key的node,检查capacity,满的话需要删掉最后一个node。然后创建新的node加到最前面。

Last updated