LRU Cache--Leetcode

Source: Internet
Author: User

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 ('ll 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 is reached its capacity, it should invalidate the least recently used item before inserting a new item.


Basic ideas:

Work with a map to find the problem.

Use list maintenance to sort by using elements. The records that are recently accessed are always moved to the linked list header.

The list stores [key, value],

The map stores the key, as well as the iterator of the corresponding node in the list.


The splice function is used when the elements in the list are moved to the front. This function is more efficient than first deleting and then inserting.


The actual execution time for this code on Leetcode is 160ms.

Class Lrucache{public:    LRUCache (int capacity): Capacity_ (capacity) {            }        int get (int key) {        Auto iter = Cache_.find (key);        if (iter = = Cache_.end ())            return-1;                Lru_.splice (Lru_.begin (), lru_, Iter->second);        Return iter->second->second;    }        void set (int key, int value) {        if (get (key)! =-1) {            Lru_.front (). second = value;            return;        }                if (lru_.size () = = capacity_) {            cache_.erase (Lru_.back (). first);            Lru_.pop_back ();        }                Lru_.push_front (Make_pair (key, value));        Cache_[key] = Lru_.begin ();    } Private:    typedef list<pair<int, int> > list_t;    typedef unordered_map<int, list_t::iterator> map_t;    list_t lru_;    map_t cache_;    const int capacity_;};


LRU Cache--Leetcode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.