Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- class LRUCache {
- public:
- int nowfirst = 1, nowlast = 1, capacity;
- unordered_map<int,int>cache,track;
- LRUCache(int capacity) {
- capacity = capacity ;
- }
- int get(int key) {
- if(cache.find(key) == cache.end())return -1;
- return cache[key];
- }
- void put(int key, int value) {
- //if capacity is 0 no insert is gonna happen
- if(capacity == 0)return;
- //capacity exceeded
- if(cache.size() == capacity){
- //new key needs to be inserted
- if(cache.find(key) == cache.end()){
- //erasing oldest key
- //finding oldest key
- auto it = cache.find(track[nowfirst]);
- //erasing oldest key-value from cache
- cache.erase(cache.find(*it));
- //erasing odlest key
- track.erase(it);
- //increasing firstnow
- firstnow++;
- }else{
- //the new key is overriding
- cache[key] = value ; //override
- }
- return;
- }
- //capacity did not exceed and new entry
- cache[key] = value ;
- if(cache.size() == 0){ //first entry
- track[nowfirst] = key;
- nowfirst++;
- }
- track[nowlast] = key;
- nowlast++;
- }
- };
- /**
- * 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);
- */
- int main(){
- cout<<"hello"<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement