How to design a latest recently used cache?
Suppose that you have visited some items. You need to design a data structure to hold these items. Each item is associated with the latest visited time.
Each time when you visit an item, check it in the data structure. If the item has been in the cache, update its visit time. Otherwise, insert it into the cache. The cache size is fixed, if it is full, delete the oldest item.
My solution:
Use a map < item, visitTime >
Initaliztion: Sort the map with f(visitTime) with descending order. O(nlg n)
If an item is visited, search it in the map with O(lg n).
If it has been in the map, update the time O(1). Sort the map O(lg n).
If not, insert it into map and then sort. O(lg n)
If map size > fixed size, delet the last element O(1).
Another solution:
Use hashtable < item , visitTime >
Sort it O(n lgn).
If an item is visited, search it in the talbe with O(1).
If it has been in the table , update the time O(1). Sort the table O(n lg n).
If not, insert it into table and then sort. O(n lg n)
If table size > fixed size, delet the last element O(1).
Are there better solutions ? O(n) ?