LRU Cache
18%
Accepted
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations:
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.
public class Solution {
// @param capacity, an integer
int capacity;
LinkedHashMap<Integer, Integer> map;
public Solution(int capacity) {
// write your code here
map = new LinkedHashMap<Integer, Integer>();
this.capacity = capacity;
}
// @return an integer
public int get(int key) {
// write your code here
if(map.containsKey(key)){
int val = map.get(key);
map.remove(key);
map.put(key, val);
return val;
}
return -1;
}
// @param key, an integer
// @param value, an integer
// @return nothing
public void set(int key, int value) {
// write your code here
if(map.containsKey(key)){
map.remove(key);
map.put(key, value);
return;
}
if (map.size() == capacity){
for(int first : map.keySet()){
map.remove(first);
break;
}
}
map.put(key, value);
}
}
No comments:
Post a Comment