https://leetcode.com/problems/lru-cache/
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.
classPair { Public intkey; Public intvalue; PublicPairintKintv) {Super(); This. Key =K; This. Value =v; } Public voidSetValue (intvalue) { This. Value =value; } }classCmpImplementsComparator { Public intCompare (Object O1, Object O2) {pair P1=(pair) O1; Pair P2=(pair) O2; if(P1.key <p2.key) {return-1; } Else if(P1.key = =p2.key) {if(P1.value = =p2.value) {return0; } Else if(P1.value <p2.value) {return-1; } Else { return1; } } Else { return1; } }} Public classLRUCache { Publicset<pair> stack =NULL; PublicHashmap<integer, integer> mapping =NULL; PublicTreemap<integer, integer> Timetokey =NULL; PublicTreemap<integer, integer> keytotime =NULL; Public intCap = 0; Public intCounter = 0; PublicLRUCache (intcapacity) { This. mapping =NewHashmap<integer, integer> (); This. Timetokey =NewTreemap<integer, integer> (); This. Keytotime =NewTreemap<integer, integer> (); This. Cap =capacity; This. Counter = 0; } Public intGetintkey) { if(!Mapping.containskey (Key)) { return-1; } Else{counter++; intValue =Mapping.get (key); intTime =Keytotime.get (key); Keytotime.put (key, counter); Timetokey.remove (time); Timetokey.put (counter, key); returnvalue; } } Public voidSetintKeyintvalue) {Counter++; if(Mapping.containskey (key)) {intTime =Keytotime.get (key); Keytotime.put (key, counter); Timetokey.remove (time); Timetokey.put (counter, key); Mapping.put (key, value); } Else { if(Mapping.size () <cap) {Mapping.put (key, value); Keytotime.put (key, counter); Timetokey.put (counter, key); } Else { intLRU =timetokey.pollfirstentry (). GetValue (); Mapping.remove (LRU); Mapping.put (key, value); Keytotime.put (key, counter); Timetokey.put (counter, key); } } }}
View Code
[email protected] [146] LRU Cache (TREEMAP)