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.
The basic idea is to use LinkedHashMap, as it has property - capacity.
publicLRUCache(int capacity){ finalint c = capacity; // make it final, so it can be used in inner class this.map = new LinkedHashMap<Integer, Integer>(c) { @Override protectedbooleanremoveEldestEntry(Map.Entry<Integer, Integer> eldest){ returnthis.size() > c; } }; }
publicintget(int key){ if (map.containsKey(key)) { int value = map.get(key); // why remove then put here? For LRU. ---- This is an ugly way, I know map.remove(key); map.put(key, value); return value; } return -1; }
publicvoidset(int key, int value){ if (map.containsKey(key)) { map.remove(key); } map.put(key, value); } }