Problem
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.
Java Solution
The key to solve this problem are using a double linked list which enables us to quickly move nodes.
Import Java.util.HashMap; public class LRUCache {private Hashmap<integer, doublelinkedlistnode> map = new Hashmap<integer, Doublelinkedlistnode> ();p rivate doublelinkedlistnode head;private doublelinkedlistnode end;private int capacity; private int len; Public LRUCache (Int. capacity) {this.capacity = Capacity;len = 0;} public int get (int key) {if (Map.containskey (key)) {Doub Lelinkedlistnode latest = Map.get (key); RemoveNode (latest); Sethead (latest); return latest.val;} else {return-1;}} public void RemoveNode (Doublelinkedlistnode node) {Doublelinkedlistnode cur = node;doublelinkedlistnode pre = Cur.pre;d Oublelinkedlistnode post = Cur.next; if (pre! = null) {Pre.next = post;} else {head = post;} if (post! = null) {Post.pre = pre;} else {end = pre;}} public void Sethead (Doublelinkedlistnode node) {node.next = Head;node.pre = Null;if (head! = null) {head.pre = node;} head = node;if (end = null) {end = node;}} public void set (int key, int value) {if (Map.containskey (key)) {DoubleliNkedlistnode OldNode = Map.get (key); oldnode.val = Value;removenode (OldNode); Sethead (OldNode);} else {Doublelinkedlistnode NewNode = new Doublelinkedlistnode (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);}}} Class Doublelinkedlistnode {public int val;public int key;public doublelinkedlistnode pre;public doublelinkedlistnode Next public Doublelinkedlistnode (int key, int value) {val = Value;this.key = key;}}
Ps:
There is a concurrency problem.
Leetcode–lru Cache (Java)