LRU Cache Policy

Source: Internet
Author: User

Topic

Design a data structure for least recently used (LRU) cache policy, which should support the following operations: Get Data (get) and write data (set).

Get Data Get (key): If there is a key in the cache, it gets its data value (usually a positive number), otherwise returns-1.

Write Data set (key, value): writes its data value if key is not yet in the cache. When the cache reaches the upper limit, it should delete the least recently used data before writing the new data to free up the idle location.

Solving

Reference links
1. Use double-linked list to record order
2. Use HashMap record Key-value
Delete Time:
Delete the values in the map and delete the nodes.

 Public classSolution {Private classnode{Node prev; Node Next;intKeyint value; Public Node(intKeyint value) { This. key = key; This.value=value; This. prev =NULL; This. Next =NULL; }    }Private intcapacity;PrivateHashmap<integer, node> hs =NewHashmap<integer, node> ();PrivateNode head =NewNode (-1, -1);PrivateNode tail =NewNode (-1, -1); Public Solution(intcapacity) { This. capacity = capacity;        Tail.prev = head;    Head.next = tail; } Public int Get(intKey) {if(!hs.containskey (key)) {return-1; }//Remove currentNode current = hs.Get(key);        Current.prev.next = Current.next; Current.next.prev = Current.prev;//Move current to tailMove_to_tail (current);returnHs.Get(key).value; } Public void Set(intKeyint value) {if(Get(key)! =-1) {HS.Get(key).value=value;return; }if(hs.size () = = capacity)            {Hs.remove (Head.next.key);            Head.next = Head.next.next;        Head.next.prev = head; } Node Insert =NewNode (Key,value);        Hs.put (key, insert);    Move_to_tail (insert); }Private void Move_to_tail(Node current)        {Current.prev = Tail.prev;        Tail.prev = current;        Current.prev.next = current;    Current.next = tail; }}

LRU Cache Policy

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.