资讯动态

华为题:LRU 缓存

发布时间:2026/10/14 3:45:03 来源:尧图企业网站定制
请你设计并实现一个满足 LRU最近最少使用缓存约束的数据结构。实现LRUCache类LRUCache(int capacity)以正整数capacity初始化 LRU 缓存。int get(int key)如果关键字key存在于缓存中则返回其值否则返回-1。void put(int key, int value)如果关键字key已存在则变更其值为value如果不存在则插入该键值对。如果插入导致容量超出则逐出最久未使用的关键字。输入描述第一行输入一个整数capacity。第二行输入一个整数m表示操作次数。接下来m行每行输入一个操作get keyput key value输出描述对于每个get操作输出查询结果。示例 1输入text2 5 put 1 1 put 2 2 get 1 put 3 3 get 2输出text1 -1C 解法cpp#include bits/stdc.h using namespace std; class LRUCache { private: int cap; listpairint,int cache; unordered_mapint, listpairint,int::iterator mp; public: LRUCache(int capacity) : cap(capacity) {} int get(int key) { if (!mp.count(key)) return -1; auto it mp[key]; int value it-second; cache.erase(it); cache.push_front({key, value}); mp[key] cache.begin(); return value; } void put(int key, int value) { if (mp.count(key)) { cache.erase(mp[key]); } else if ((int)cache.size() cap) { int oldKey cache.back().first; cache.pop_back(); mp.erase(oldKey); } cache.push_front({key, value}); mp[key] cache.begin(); } }; int main() { int capacity; cin capacity; int m; cin m; LRUCache lru(capacity); while (m--) { string op; cin op; if (op get) { int key; cin key; cout lru.get(key) endl; } else if (op put) { int key, value; cin key value; lru.put(key, value); } } return 0; }

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑