For LRUCache, the basic operations include:
- get the value of a key, and mark it as the most recently used key
- update the existing (key, value) pair
- add the new key and its value into the cache, and potentially evict the least recently used key if out of capacity
One common solution is to use doubly linked list to maintain the key usage status (move 1 element to the tail, add 1 element to the tail, remove 1 element from the head all takes O(1)), while using hashmap of (key, pointer of list element) to query and update the key (get, set takes O(1)).
If you replace doubly linked list with array, move 1 element to the tail will take O(n).
If you replace doubly linked list with heap or binary search trea, remove 1 element from the head will always take O(log(n)). So they are not good alternatives of doubly linked list.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…