题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
public class Solution {
/**
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
public Map.Entry<Integer,Integer> getHead(LinkedHashMap map) {
return (Map.Entry<Integer,Integer>)map.entrySet().iterator().next();
}
public int[] LRU (int[][] operators, int k) {
// write code here
LinkedHashMap<Integer,Integer> map = new LinkedHashMap<>();
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<operators.length;i++){
if(operators[i][0]==1){
if(map.containsKey(operators[i][1]))
map.remove(operators[i][1]);
if(map.size()>=k)
map.remove(getHead(map).getKey());
map.put(operators[i][1],operators[i][2]);
}else{
if(map.containsKey(operators[i][1])){
int value = map.get(operators[i][1]);
map.remove(operators[i][1]);
map.put(operators[i][1],value);
list.add(value);
}else{
list.add(-1);
}
}
}
int []array = new int[list.size()];
for(int i=0;i<array.length;i++){
array[i] = list.get(i);
}
return array;
}
}