题解 | #设计LRU缓存结构#c++/python3/java (1)调库 (2)手撸双向链表
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
描述
设计LRU(最近最少使用)缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能
- set(key, value):将记录(key, value)插入该结构
- get(key):返回key对应的value值
提示:
1.某个key的set或get操作一旦发生,认为这个key的记录成了最常使用的,然后都会刷新缓存。
2.当缓存的大小超过K时,移除最不经常使用的记录。
3.输入一个二维数组与K,二维数组每一维有2个或者3个数字,第1个数字为opt,第2,3个数字为key,value
若opt=1,接下来两个整数key, value,表示set(key, value)
若opt=2,接下来一个整数key,表示get(key),若key未出现过或已被移除,则返回-1
对于每个opt=2,输出一个答案
4.为了方便区分缓存里key与value,下面说明的缓存里key用""号包裹
进阶:你是否可以在O(1)的时间复杂度完成set和get操作
示例1
输入:
[[1,1,1],[1,2,2],[1,3,2],[2,1],[1,4,4],[2,2]],3
复制
返回值:
[1,-1]
复制
说明:
[1,1,1],第一个1表示opt=1,要set(1,1),即将(1,1)插入缓存,缓存是{"1"=1}
[1,2,2],第一个1表示opt=1,要set(2,2),即将(2,2)插入缓存,缓存是{"1"=1,"2"=2}
[1,3,2],第一个1表示opt=1,要set(3,2),即将(3,2)插入缓存,缓存是{"1"=1,"2"=2,"3"=2}
[2,1],第一个2表示opt=2,要get(1),返回是[1],因为get(1)操作,缓存更新,缓存是{"2"=2,"3"=2,"1"=1}
[1,4,4],第一个1表示opt=1,要set(4,4),即将(4,4)插入缓存,但是缓存已经达到最大容量3,移除最不经常使用的{"2"=2},插入{"4"=4},缓存是{"3"=2,"1"=1,"4"=4}
[2,2],第一个2表示opt=2,要get(2),查找不到,返回是[1,-1]
示例2
输入:
[[1,1,1],[1,2,2],[2,1],[1,3,3],[2,2],[1,4,4],[2,1],[2,3],[2,4]],2
复制
返回值:
[1,-1,-1,3,4]
复制
备注:
1 \leq K \leq N \leq 10^51≤K≤N≤10
5
-2 \times 10^9 \leq x,y \leq 2 \times 10^9−2×10
9
≤x,y≤2×10
9
思路和心得:
(一)调库
python3代码
# # lru design # @param operators int整型二维数组 the ops # @param k int整型 the k # @return int整型一维数组 # import collections class Solution: def LRU(self , operators , k ): # write code here od = collections.OrderedDict() res = [] for op in operators: if op[0] == 1: key = op[1] value = op[2] if key in od: od.move_to_end(key) od[key] = value if len(od) > k: od.popitem(last = False) else: key = op[1] if key not in od: res.append(-1) else: od.move_to_end(key) res.append(od[key]) return res
c++ []
class Solution { public: /** * lru design * @param operators int整型vector<vector<>> the ops * @param k int整型 the k * @return int整型vector */ vector<int> LRU(vector<vector<int> >& operators, int k) { // write code here list<pair<int, int>> list1; unordered_map<int, list<pair<int,int>>:: iterator> key_list_ptr; vector<int> res; for (auto op : operators) { if (op[0] == 1) { int key = op[1], value = op[2]; if (key_list_ptr.find(key) != key_list_ptr.end()) { list1.erase(key_list_ptr[key]); } list1.push_back(pair<int,int>{key, value}); key_list_ptr[key] = -- list1.end(); if ((int)list1.size() > k) { key_list_ptr.erase(list1.begin()->first); list1.pop_front(); } } else { int key = op[1]; if (key_list_ptr.find(key) == key_list_ptr.end()) res.push_back(-1); else { auto [k, v] = *key_list_ptr[key]; list1.erase(key_list_ptr[key]); list1.push_back(pair<int, int>{k, v}); key_list_ptr[key] = --list1.end(); res.push_back(v); } } } return res; } };
java []
import java.util.*; public class Solution { /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ public int[] LRU (int[][] operators, int k) { // write code here int on = operators.length; int rn = 0; for (int i = 0; i < on; i ++) if (operators[i][0] == 2) rn ++; Map <Integer, Integer> link_map = new LinkedHashMap<>(); int [] res = new int [rn]; int ri = 0; for (int [] op : operators) { if (op[0] == 1) { int key = op[1], value = op[2]; if (link_map.containsKey(key) == true) { link_map.remove(key); } link_map.put(key, value); if (link_map.size() > k) { link_map.remove(link_map.entrySet().iterator().next().getKey()); } } else { int key = op[1]; if (link_map.containsKey(key) == false) { res[ri ++] = -1; } else { int val = link_map.remove(key); link_map.put(key, val); res[ri ++] = val; } } } return res; } }
(二)哈希+手撸双向链表
python3 []
# # lru design # @param operators int整型二维数组 the ops # @param k int整型 the k # @return int整型一维数组 # class double_link_node: def __init__(self, key: int, val: int): self.key = key self.val = val self.prev = None self.next = None class double_link_list: def __init__(self): self.head = double_link_node(0, 0) self.tail = double_link_node(0, 0) self.head.next = self.tail self.tail.prev = self.head def move_to_end(self, p: double_link_node) -> None: p.prev.next = p.next p.next.prev = p.prev p.prev = self.tail.pre***ext = self.tail self.tail.prev.next = p self.tail.prev = p def append_end(self, key: int, value: int) -> None: p = double_link_node(key, value) p.prev = self.tail.pre***ext = self.tail self.tail.prev.next = p self.tail.prev = p class Solution: def LRU(self , operators , k ): # write code here dl = double_link_list() key_dl_ptr = dict() res = [] for op in operators: if op[0] == 1: key = op[1] value = op[2] if key in key_dl_ptr: p = key_dl_ptr[key] p.val = value dl.move_to_end(p) else: dl.append_end(key, value) key_dl_ptr[key] = dl.tail.prev if len(key_dl_ptr) > k: p = dl.head.next dl.head.next = p.next p.next.prev = dl.head del key_dl_ptr[p.key] else: key = op[1] if key not in key_dl_ptr: res.append(-1) else: p = key_dl_ptr[key] dl.move_to_end(p) res.append(p.val) return res
c++ []
struct double_link_list_node{ int key; int val; double_link_list_node * prev; double_link_list_node * next; double_link_list_node(int key_, int val_) { key = key_; val = val_; prev = NULL; next = NULL; } }; class double_link_list { public: double_link_list_node * head; double_link_list_node * tail; double_link_list() { head = new double_link_list_node(0, 0); tail = new double_link_list_node(0, 0); head->next = tail; tail->prev = head; } void move_to_end(double_link_list_node * p) { //----先摘下来 p->prev->next = p->next; p->next->prev = p->prev; //----挂到后面 p->prev = tail->prev; p->next = tail; tail->prev->next = p; tail->prev = p; } void append_end(int key, int value) { double_link_list_node * p = new double_link_list_node(key, value); p->prev = tail->prev; p->next = tail; tail->prev->next = p; tail->prev = p; } }; class Solution { public: /** * lru design * @param operators int整型vector<vector<>> the ops * @param k int整型 the k * @return int整型vector */ vector<int> LRU(vector<vector<int> >& operators, int k) { // write code here double_link_list dl = double_link_list(); unordered_map<int, double_link_list_node *> key_dl_node; vector<int> res; for (auto & op : operators) { if (op[0] == 1) { int key = op[1]; int value = op[2]; if (key_dl_node.find(key) != key_dl_node.end()) { auto p = key_dl_node[key]; p->val = value; dl.move_to_end(p); } else { dl.append_end(key, value); key_dl_node[key] = dl.tail->prev; } if ((int)key_dl_node.size() > k) { double_link_list_node * p = dl.head->next; dl.head->next = p->next; p->next->prev = dl.head; key_dl_node.erase(p->key); } } else { int key = op[1]; if (key_dl_node.find(key) == key_dl_node.end()) { res.push_back(-1); } else { double_link_list_node * p = key_dl_node[key]; res.push_back(p->val); dl.move_to_end(p); } } } return res; } };
java []
import java.util.*; class double_link_list_node { int key; int val; double_link_list_node prev; double_link_list_node next; double_link_list_node() {} double_link_list_node(int key_, int val_) { key = key_; val = val_; prev = null; next = null; } } class double_link_list { double_link_list_node head; double_link_list_node tail; double_link_list() { head = new double_link_list_node(0, 0); tail = new double_link_list_node(0, 0); head.next = tail; tail.prev = head; } void move_to_end(double_link_list_node p) { //----先摘下来 p.prev.next = p.next; p.next.prev = p.prev; //----挂到最后 p.prev = tail.pre***ext = tail; tail.prev.next = p; tail.prev = p; } void append_end(int key, int value) { double_link_list_node p = new double_link_list_node(key, value); p.prev = tail.pre***ext = tail; tail.prev.next = p; tail.prev = p; } } public class Solution { /** * lru design * @param operators int整型二维数组 the ops * @param k int整型 the k * @return int整型一维数组 */ public int[] LRU (int[][] operators, int k) { // write code here double_link_list dl = new double_link_list(); Map<Integer, double_link_list_node> key_dl_node = new HashMap<>(); List<Integer> res_tmp = new ArrayList<>(); for (int [] op : operators) { if (op[0] == 1) { int key = op[1]; int value = op[2]; if (key_dl_node.containsKey(key) == true) { double_link_list_node p = key_dl_node.get(key); p.val = value; dl.move_to_end(p); } else { dl.append_end(key, value); key_dl_node.put(key, dl.tail.prev); if (key_dl_node.size() > k) { double_link_list_node p = dl.head.next; dl.head.next = p.next; p.next.prev = dl.head; key_dl_node.remove(p.key); } } } else { int key = op[1]; if (key_dl_node.containsKey(key) == false) { res_tmp.add(-1); } else { double_link_list_node p = key_dl_node.get(key); res_tmp.add(p.val); dl.move_to_end(p); } } } int rn = res_tmp.size(); int [] res = new int [rn]; for (int i = 0; i < rn; i ++) { res[i] = res_tmp.get(i); } return res; } }