简体   繁体   English

什么可能导致此LRU实现中的运行时错误(哈希映射和双向链接列表)?

[英]What could cause runtime error in this LRU implementation (hashmap and doubly-linked list)?

I'm getting a runtime error on LeetCode, but this works fine on my Linux system in 0.046 user time for largest testcase. 我在LeetCode上遇到运行时错误,但这在Linux系统上以0.046个用户时间(最大的测试用例)正常运行。 The output matches exactly the expected output on LeetCode. 输出与LeetCode上的预期输出完全匹配。 My solution uses a hashmap and a doubly linked list. 我的解决方案使用哈希图和双向链表。 The hashmap stores an iterator to the linked list node (in addition to the key->value pair) so that the list can be updated O(1) instead of O(n). 哈希图将迭代器存储到链接列表节点(除了键->值对之外),以便可以将列表更新为O(1)而不是O(n)。 Got it to work for several testcases, but I get a runtime error on testcase with cache size 512 and 2019 instructions. 使它适用于多个测试用例,但是在缓存大小为512和2019的指令的测试用例上出现运行时错误。

class LRUCache {
public:
    LRUCache(int _capacity) { capacity = _capacity; }    
    int get(int key) {
        if(hmap.find(key) == hmap.end()) return -1;
        addq(key);
        return hmap[key].first;
    }    
    void put(int key, int value) {
        list<int>::iterator ptr = addq(key);
        hmap[key] = make_pair(value, ptr);
    }
private:
    list<int> q;
    unordered_map<int, pair<int,list<int>::iterator>> hmap;
    int capacity;
    list<int>::iterator addq(int key) {
        if(hmap.find(key) == hmap.end()) {
            if(q.size() == capacity) {
                int to_pop = q.back();
                hmap.erase(to_pop);
                q.pop_back();
            }                        
        }
        else q.erase(hmap[key].second);
        return q.insert(q.begin(), key);
    }
};

There is a problem with your get (int key) function. 您的get (int key)功能有问题。 When you access the cache you have to invalidate the entry and update your iterators. 当您访问缓存时,必须使条目无效并更新迭代器。 You do that with your addq function but never update the corresponding entry in your hmap . 你这样做,你的addq功能,但从来没有更新您的相应条目hmap Therefore a runtime error occurs because you then access an iterator which has already been invalidated by your addq function. 因此,发生运行时错误是因为您随后访问了一个已被您的addq函数无效的迭代器。

Looking at the following snippet: 查看以下代码段:

if(hmap.find(key) == hmap.end()) return -1;
addq(key);
return hmap[key].first;

The addq returns an iterator, but you never update the iterator in your map, so this should be : addq返回一个迭代器,但是您永远不会在地图中更新该迭代器,因此应为:

hmap[key].second = addq(key);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM