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.
Import Java.util.hashmap;import Java.util.linkedlist;class listnode{int key, value; ListNode Next, Prev;public ListNode () {This.key = This.value = 0;next = prev = null;} public ListNode (int key, int val) {This.key = Key;this.value = Val;next = prev = null;}} public class LRUCache {private ListNode head,tail;private Hashmap<integer, listnode> hashmap;private int size, CAPA City;public static void Main (string[] args) {//TODO auto-generated method stub}public LRUCache (int capacity) {thi s.size = 0; This.capacity = capacity; Head = new ListNode (); tail = new ListNode (); Head.next = tail; Tail.prev = head; HashMap = new Hashmap<integer, listnode> (); } public int get (int key) {if (Hashmap.containskey (key)) {ListNode cur = hashmap.get (key);//detach the node In the Listcur.prev.next = Cur.next;cur.next.prev = Cur.prev;//set The visting node is the Firstnode.listnode tmp = head. Next;head.next = Cur;cur.prev = Head;cur.next = Tmp;tmp.prev = Cur;return cur.value;} else return-1; } public void set (int key, int value) {if (Hashmap.containskey (key)) {ListNode cur = hashmap.get (key); cur.v Alue = Value;//detachcur.prev.next = Cur.next;cur.next.prev = Cur.prev;//set The visting node be the Firstnode.listnode TM p = Head.next;head.next = Cur;cur.prev = Head;cur.next = Tmp;tmp.prev = cur;} else {if (size = = capacity) {ListNode last = Tail.prev;hashmap.remove (last.key); tail = Last;last = null;size--;} ListNode cur = new ListNode (key, value); Hashmap.put (key, cur);//set The new node be the Firstnode.listnode tmp = Head.next ; head.next = Cur;cur.prev = Head;cur.next = Tmp;tmp.prev = cur;size++;} }}
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
"Leetcode" LRU Cache