*LRU Cache

Source: Internet
Author: User

Topic:

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.

Exercises

This problem is a data structure design problem, in Leetcode inside is such a, or is quite classic a problem, can take a good look.

This problem requires designing the data structure of the LRU cache to implement the set and get functions. Learning about the operating system should know that caching as a cache can help to quickly access data, but is determined to be less capacity. The basic idea of the cache type that the problem requires to implement is that "the most recently used data is more likely to be reused than it used to be Lru,lru", and is a more efficient cache type.

The way to solve this problem is: doubly linked list +hashmap.

"To be able to quickly delete data items that have not been accessed for the longest time and insert the most recent data items, we connect the doubly linked list to the data items in the cache and ensure that the list maintains the order of the data items from the most recent access to the oldest. Each time a data item is queried, the data item is moved to the list header (O (1) time complexity). In this way, after multiple lookups, the most recently used content moves to the head of the linked list, and the content that is not used is moved behind the list. When a replacement is needed, the last position of the list is the least recently used data item, we only need to put the most recent data item in the list head, when the cache full, the end of the list of obsolete list is. ”

Note: The use of the doubly linked list is based on two considerations.

The first is that the hit of the block in the cache may be random, regardless of the order in which the load comes in.

Second, the two-way linked list is inserted, deleted quickly, you can flexibly adjust the order of each other, the time complexity of O (1). ”

The characteristics of LRU are solved, and the time complexity of the algorithm is now considered. In order to reduce the time complexity of the whole data structure, it is necessary to reduce the time complexity of the search, so we use HashMap to do so, so the time Su Read is O (1).

So for the subject:

Get (Key): Returns 1 if no value for get is present in the cache, returns its value if there is a value to find in the cache, and deletes it in the original linked list, and then takes it as a head node.

Set (Key,value): When the key value of the set is already present, it updates its value, deletes it in the original linked list, and then takes it as the head node, and creates a new node if the key value of the medicine set does not exist, if the current len<capacity, Add it to hashmap and use it as the head node to update len length, otherwise delete the last node of the list and put it in HashMap as the head node, but Len does not update.

The principle is: to have access to the linked list, you need to update the list order.

classDoublelinkedlistnode { Public intVal;  Public intkey;  PublicDoublelinkedlistnode Pre;  PublicDoublelinkedlistnode Next;  PublicDoublelinkedlistnode (intKeyintvalue) {Val=value;  This. Key =key; }}     Public classLRUCache {PrivateHashmap<integer, doublelinkedlistnode>Map=NewHashmap<integer, doublelinkedlistnode>(); PrivateDoublelinkedlistnode Head; PrivateDoublelinkedlistnode end; Private intcapacity; Private intLen;  PublicLRUCache (intcapacity) {         This. Capacity =capacity; Len= 0; }         Public intGetintkey) {        if(Map.containskey (key)) {Doublelinkedlistnode Latest=Map.get (key);            RemoveNode (latest);            Sethead (latest); returnLatest.val; }        Else return-1; }         Public voidSetintKeyintvalue) {        if(Map.containskey (key)) {Doublelinkedlistnode OldNode=Map.get (key); Oldnode.val=value;            RemoveNode (OldNode);        Sethead (OldNode); }        Else{Doublelinkedlistnode NewNode=NewDoublelinkedlistnode (key, value); if(len<capacity)                {Sethead (NewNode);                Map.put (Key,newnode); Len++; }            Else{map.remove (End.key); End=End.pre; if(End! =NULL) {End.next=NULL;                } sethead (NewNode);                        Map.put (Key,newnode); }        }    }         Public voidRemoveNode (Doublelinkedlistnode node) {doublelinkedlistnode cur=node; Doublelinkedlistnode Pre=Node.pre; Doublelinkedlistnode Next=Node.next; if(pre!=NULL) {Pre.next=Next; //next.pre = pre; next May null!        }        Else{Head=Next; }                if(next!=NULL) {Next.pre=Pre; //pre.next = next;?        }        Else{End=Pre; }    }         Public voidSethead (Doublelinkedlistnode node) {Node.next=Head; Node.pre=NULL; //head.pre = node;        if(Head! =NULL) {Head.pre= node;//Head may null!empty LinkedList} head=node; if(end==NULL) {End=node; }            }}

*LRU Cache

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.