Got time limit exceeded and did not know why.
As shown in the code, I want to use Hashmap to store the key-value pairs and use Arraylist to store the keys in the LRU order.
import java.util.*;
public class LRUCache {
HashMap<Integer, Integer> cacheMap; // key, value
ArrayList<Integer> cacheList; // key
int capacity;
public LRUCache(int capacity) {
this.cacheMap = new HashMap<Integer, Integer>();
this.cacheList = new ArrayList<Integer>();
this.capacity = capacity;
}
public int get(int key) {
if (this.cacheMap.containsKey(key)) {
this.cacheList.remove(new Integer(key));
this.cacheList.add(key);
return this.cacheMap.get(key);
}
return -1;
}
public void set(int key, int value) {
if (!this.cacheMap.containsKey(key)) {
if (this.capacity == this.cacheList.size()) {
this.cacheMap.remove(this.cacheList.get(0));
this.cacheList.remove(0);
}
this.cacheList.add(key);
this.cacheMap.put(key, value);
} else {
this.cacheMap.remove(key);
this.cacheMap.put(key, value);
this.cacheList.remove(new Integer(key));
this.cacheList.add(key);
}
}
}