TLE ? please help ...


  • 0
    L
    class Node {
        int mKey;
        int mValue;
        
    public:
        Node (int key, int value) {
             mKey = key;
             mValue = value;
        }   
        
        int getValue (int key) {
            if (key == mKey) {
                return mValue;
            } else {
                return -1;
            }
        }
    };
    
    class LRUCache{
        int mCapacity;
        vector<Node*> mCache;
    public:
        LRUCache(int capacity) {
            mCapacity = capacity;
        }
        
        int get(int key) {
            for (vector<Node*>::iterator it = mCache.begin(); it != mCache.end(); it++) {
                int temp = (*it)->getValue(key);
                if (temp != -1) {
                    mCache.erase(it);
                    mCache.insert(mCache.begin(), new Node(key, temp));
                    return temp;
                }
            }
            return -1;
        }
        
        void set(int key, int value) {
            for (auto it = mCache.begin(); it != mCache.end(); it++) {
                int temp = (*it)->getValue(key);
                if (temp != -1) {
                    mCache.erase(it);
                    break;
                }
            }
            mCache.insert(mCache.begin(), new Node(key, value));
            if (mCache.size() > mCapacity) {
                mCache.pop_back();
            }
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.