get
and set
.
get(key)
- Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.set(key, value)
- Set or insert the value if the key is not
already present. When the cache reached its capacity, it should
invalidate the least recently used item before inserting a new item.解题思路:
1. 要求每次查询元素要constant-time,则我们想到要用hashmap
2. 要每次能返回least recently used cache, 则我们想到要用queue或者linkedlist
则合起来则用linkedhahsmap
注意:每次get, 或者set都要把已经存在的此元素挪到后面去,因为这些操作为调用了cache
Java Code:
public class LRUCache { private int totalCapacity; LinkedHashMaplinkedHashMap = new LinkedHashMap (); private int num; public LRUCache(int capacity){ this.totalCapacity = capacity; this.num = 0; } public int get(int key){ int value = -1; if (linkedHashMap.containsKey(key)){ value = linkedHashMap.get(key); linkedHashMap.remove(key); linkedHashMap.put(key, value); } return value; } public void set(int key, int value){ if (linkedHashMap.containsKey(key)){ linkedHashMap.remove(key); linkedHashMap.put(key, value); return; } if(this.num == this.totalCapacity){ Iterator keys= linkedHashMap.keySet().iterator(); linkedHashMap.remove(keys.next()); this.num--; } this.num++; linkedHashMap.put(key, value); } }
No comments:
Post a Comment