[英]What could cause runtime error in this LRU implementation (hashmap and doubly-linked list)?
我在LeetCode上遇到運行時錯誤,但這在Linux系統上以0.046個用戶時間(最大的測試用例)正常運行。 輸出與LeetCode上的預期輸出完全匹配。 我的解決方案使用哈希圖和雙向鏈表。 哈希圖將迭代器存儲到鏈接列表節點(除了鍵->值對之外),以便可以將列表更新為O(1)而不是O(n)。 使它適用於多個測試用例,但是在緩存大小為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);
}
};
您的get (int key)
功能有問題。 當您訪問緩存時,必須使條目無效並更新迭代器。 你這樣做,你的addq
功能,但從來沒有更新您的相應條目hmap
。 因此,發生運行時錯誤是因為您隨后訪問了一個已被您的addq
函數無效的迭代器。
查看以下代碼段:
if(hmap.find(key) == hmap.end()) return -1;
addq(key);
return hmap[key].first;
addq
返回一個迭代器,但是您永遠不會在地圖中更新該迭代器,因此應為:
hmap[key].second = addq(key);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.