forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
943c28a
commit a0cc867
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
class LRUCache { | ||
unordered_map<int,int>Map; | ||
list<int>List; | ||
unordered_map<int,list<int>::iterator>iter; | ||
int cap; | ||
|
||
public: | ||
LRUCache(int capacity) | ||
{ | ||
cap=capacity; | ||
} | ||
|
||
int get(int key) | ||
{ | ||
if (Map.find(key)==Map.end()) return -1; | ||
|
||
List.erase(iter[key]); | ||
List.push_back(key); | ||
iter[key]=--List.end(); | ||
return Map[key]; | ||
} | ||
|
||
void put(int key, int value) | ||
{ | ||
if (cap<=0) return; | ||
if (get(key)!=-1) | ||
{ | ||
Map[key]=value; | ||
return; | ||
} | ||
|
||
if (List.size()<cap) | ||
{ | ||
List.push_back(key); | ||
iter[key]=--List.end(); | ||
Map[key]=value; | ||
} | ||
else | ||
{ | ||
int minKey = List.front(); | ||
iter.erase(minKey); | ||
List.pop_front(); | ||
Map.erase(minKey); | ||
|
||
List.push_back(key); | ||
iter[key]=--List.end(); | ||
Map[key]=value; | ||
} | ||
|
||
} | ||
}; | ||
|
||
/** | ||
* Your LRUCache object will be instantiated and called as such: | ||
* LRUCache obj = new LRUCache(capacity); | ||
* int param_1 = obj.get(key); | ||
* obj.put(key,value); | ||
*/ |