Visual Studio passed but leetcode return Runtime Error: Last executed input: 1,[set(2,1),get(1)]


  • 0
    H

    I know the age map is not efficient for search, just want a working solution first before optimizing. But the following code cannot even pass the simple test case (Visual Studio 2008 passed and return -1 for above test case.

    Does anyone know where is the problem?

        class LRUCache{
        public:
        	int capacity;
        	unordered_map<int, int> values;
        	unordered_map<int, unsigned long> ages;
        	LRUCache(int capacity) {
        		this->capacity = capacity;
        	}
        	void touch(int key) {
        		ages[key] = clock();
        	}
        	int LRU() {
        		typedef unordered_map<int, unsigned long>::iterator myIter;
        		unsigned long age = 0xffffffff;
        		int key;
        		for (myIter it=ages.begin(); it!=ages.end(); ++it)
        			if (it->second < age) {
        				key = it->first;
        				age = it->second;
        			}
        		return key;
        	}
        	int get(int key) {
        		if (values.find(key)!=values.end()) {
        			touch(key);
        			return values[key];
        		} else return -1;
        	}
        	void set(int key, int value) {
        		if (values.find(key) == values.end() && values.size() == capacity) {
        			int key = LRU();
        			values.erase(key);
        			ages.erase(key);
        		}
        		values[key] = value;
        		touch(key);
        	}
        };
    
    int main ()
    {
    	LRUCache cache(1);// Runtime Error Last executed input:	1,[set(2,1),get(1)]
    	cache.set(2, 1);
    	std::cout << "LRUCache: cache.get(1)=" << cache.get(1) << endl;
    	return 0;
    }

Log in to reply
 

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