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