题目描述
大名鼎鼎的超高频面试题 太感动,在这道题上花了太多时间了,今天终于补上博客了TvT
思路 & 代码
结构用的是:双向链表 + 哈希表 。可以满足O(1)时间复杂度 put():key存在则delete,然后再put;否则直接put get():key存在则保存值,然后put(放到前面,顺带删除原结点,复用代码) 查找的O(1):通过HashMap实现,以及伪尾结点 (removeLast) 删除的O(1):通过双向链表实现 tips:伪头结点、伪尾结点 (避免了检查相邻结点是否为null,不装入map)
class LRUCache { class DoubleListNode { int val; int key; DoubleListNode pre; DoubleListNode next; DoubleListNode ( ) { } DoubleListNode ( int keyy, int value) { key = keyy; val = value; } } int cap; int size; HashMap < Integer , DoubleListNode > map; DoubleListNode head, tail; public LRUCache ( int capacity) { cap = capacity; size = 0 ; map = new HashMap ( ) ; head = new DoubleListNode ( ) ; tail = new DoubleListNode ( ) ; head. next = tail; tail. pre = head; } public int get ( int key) { DoubleListNode now = map. get ( key) ; if ( now != null ) { int getNum = now. val; put ( now. key, now. val) ; return getNum; } return - 1 ; } void removeNode ( DoubleListNode removeN) { size-- ; removeN. pre. next = removeN. next; removeN. next. pre = removeN. pre; map. remove ( removeN. key, removeN) ; } public void put ( int key, int value) { if ( map. containsKey ( key) ) { removeNode ( map. get ( key) ) ; } DoubleListNode nowN = new DoubleListNode ( key, value) ; nowN. pre = head; nowN. next = head. next; head. next. pre = nowN; head. next = nowN; size++ ; map. put ( key, nowN) ; if ( size > cap) { removeNode ( tail. pre) ; } }
}
LinkedHashMap 的写法
class LRUCache { private int cap; private Map < Integer , Integer > map = new LinkedHashMap < > ( ) ; public LRUCache ( int capacity) { this . cap = capacity; } public int get ( int key) { if ( map. keySet ( ) . contains ( key) ) { int value = map. get ( key) ; map. remove ( key) ; map. put ( key, value) ; return value; } return - 1 ; } public void put ( int key, int value) { if ( map. keySet ( ) . contains ( key) ) { map. remove ( key) ; } if ( map. size ( ) == cap) { Iterator < Map. Entry < Integer , Integer > > iterator = map. entrySet ( ) . iterator ( ) ; iterator. next ( ) ; iterator. remove ( ) ; } map. put ( key, value) ; }
}