public class Solution {
/**
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
public int[] LRU (int[][] operators, int k){
// write code here
if( k <= 0 || operators == null){
return null;
}
int resultLength = 0;
for(int i = 0;i< operators.length;i++){
if(operators[i][0] == 2){
resultLength ++;
}
}
int index = 0;
int[] result = new int[resultLength];
MyLruCache<Integer,Integer> cache = new MyLruCache<>(k);
for(int i = 0;i<operators.length;i++){
switch(operators[i][0]){
case 1:
cache.set(operators[i][1],operators[i][2]);
break;
case 2:
result[index ++] = cache.get(operators[i][1]) == null ? -1 : cache.get(operators[i][1]);
break;
default:
break;
}
}
return result;
}
public class MyLruCache<K,V>{
private int cacheSize;
private float factory = 0.75f;
private LinkedHashMap<K,V> map;
public MyLruCache(int cacheSize) {
this.cacheSize = cacheSize;
map = new LinkedHashMap<K,V>(cacheSize, factory, true){
protected boolean removeEldestEntry(Map.Entry<K, V> eldest){
return size() > MyLruCache.this.cacheSize;
};
};
}
public V get(K key){
return map.get(key);
}
public void set(K key,V value){
map.put(key,value);
}
}
}