146. LRU Cache
# Medium
很有意思的一道题。理解题意:1)初始化缓存空间大小;2)get
函数获取这个cache
,并且把这个key
设置为最近使用的项;3)put
函数更新或添加这个cache
,并且把这个key
设置为最近使用的项,如果cache
内存空间已满,则移除最不常使用的项添加新的项
key idea: what data structure want to use
Solution 1(非常笨的办法):
hashMap = {key: [value, level]}
, low level means the least recently used.
update levels while doing get/put operations. Complicated.
Solution 2 (queue manages priority, 效率提高但依然不够快):
hashMap = {key: value}
, queue is cache space, adjust the position of keys according to get/put
operations. Simplify to say, when get/put
key, queue.pop(key) -> queue.append(key)
, if want to remove the least recently used, queue.pop(0)
总结,更新least recently used秩序的时候可以继续优化时间,用link list
是最好的方法,但没有尝试
关于Python3 知识点:
dictionary:
for key in dic
for key, value in dic.items()
list:
list.remove(value)
, the first value in listlist[index] = list.pop(index)
, have return value and remove this element, can without return valuelist.append(value)
, add value at the end of the listlist.extend(list2)
, flat adding to listlist.append(subList[:])
, add whole sublist to nested list
Last updated