Untitled

 avatar
unknown
plain_text
a year ago
2.0 kB
3
Indexable
class LRUCache {
    vector<int> vec;
    unordered_map<int, vector<int>::iterator> keyIter;
    unordered_map<int, int> keyValue; 
    int cap;
public:
    LRUCache(int capacity) {
        cap = capacity;
    }
    
    int get(int key) {
        if(keyValue.find(key)==keyValue.end()) {
            return -1;
        }
        vec.erase(keyIter[key]);
        vec.push_back(key);
        keyIter[key] = --vec.end();
        return keyValue[key];
    }
    
    void put(int key, int value) {
        if(get(key)!=-1){
            keyValue[key] = value;
            return;
        }
        // new key
        if(keyValue.size()==cap){
            // remove first one
            int keyDel = vec[0];
            vec.erase(vec.begin());
            keyIter.erase(keyDel);
            keyValue.erase(keyDel);
        }
        vec.push_back(key);
        keyValue[key] = value;
        keyIter[key] = --vec.end();
    }
};

/**
 * 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);
 */

==
"""
Runtime Error
=================================================================
==23==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000074 at pc 0x55eb075855b1 bp 0x7ffd131e3850 sp 0x7ffd131e3010
READ of size 68 at 0x502000000074 thread T0
    #6 0x7f4112b01d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
    #7 0x7f4112b01e3f  (/lib/x86_64-linux-gnu/libc.so.6+0x29e3f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
0x502000000074 is located 0 bytes after 4-byte region [0x502000000070,0x502000000074)
freed by thread T0 here:
    #6 0x7f4112b01d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
previously allocated by thread T0 here:
    #6 0x7f4112b01d8f  (/lib/x86_64-linux-gnu/libc.so.6+0x29d8f) (BuildId: c289da5071a3399de893d2af81d6a30c62646e1e)
"""
Leave a Comment