Design and implement a data structure forLeast recently Used (LRU) cache. It should support the following operations:Getand put.Get(key)-Get the value ('ll always be positive) of the keyifThe key existsinchThe cache, otherwisereturn-1. Put (key, value)-Set or insert the valueifThe key isnot already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting aNewitem. Follow Up:could You DoBoth operationsinchO (1) Time complexity?Example:lrucache Cache=NewLRUCache (2 /*capacity*/); Cache.put (1,1); Cache.put (2,2); cache.Get(1);//returns 1Cache.put (3,3);//evicts Key 2Cache.Get(2);//returns-1 (not found)Cache.put (4,4);//evicts Key 1Cache.Get(1);//returns-1 (not found)Cache.Get(3);//returns 3Cache.Get(4);//returns 4
Key values to think of HashMap, adding and removing nodes to consider the list, + the tail node, so to construct the corresponding class
public class LRUCache {private class node{int key; int value; Node Pre; Node Next; public Node (int key, int value) {This.key = key; This.value = value; This.pre = null; This.next = null; }} private int capacity; Private node head = new Node (-1,-1); Private node Tail = new Node (-1,-1); Hashmap<integer, node> map = new hashmap<> (); public LRUCache (int capacity) {this.capacity = capacity; Head.next = tail; Tail.pre = head; } public int get (int key) {if (!map.containskey (key)) {return-1; } Node cur = map.get (key); Cur.pre.next = Cur.next; Cur.next.pre = Cur.pre; Movetotail (cur); return cur.value; } public void put (int key, int value) {if (Get (key)! =-1) {Map.get (key). value = value; Return } Node cur = new node(key, value); if (map.size () = = capacity) {Map.Remove (Head.next.key); Head.next.next.pre = head; Head.next = Head.next.next; } map.put (key, cur); Movetotail (cur); } private void Movetotail (Node cur) {tail.pre.next = cur; Cur.pre = Tail.pre; Tail.pre = cur; Cur.next = tail; }}/** * Your LRUCache object would be instantiated and called as such: * LRUCache obj = new LRUCache (capacity); * int param_1 = Obj.get (key); * Obj.put (Key,value); */
146. LRU Cache