用双哈希解决该问题
设计LRU缓存结构
http://www.nowcoder.com/questionTerminal/e3769a5f49894d49b871c09cadd13a61
import java.util.*;
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
Map<Integer,Integer> tempMap1 = new HashMap<Integer, Integer>();//存储key与value
Map<Integer,Integer> tempMap2 = new HashMap<Integer, Integer>();//存储优先级
ArrayList<Integer> array = new ArrayList<Integer>();
for(int i = 0;i<operators.length;i++){
if(operators[i][0]==1){
tempMap1.put(operators[i][1],operators[i][2]);//存储key与对应的value
tempMap2.put(operators[i][1],getMaxPriority(tempMap2)+1);//存储存贮key,然后赋值优先级,每次访问的时候,设置给当前最大优先级+1
if(tempMap1.size()>k){
tempMap1.remove(getMin(tempMap2));//得到优先级最小的key并且删除
}
}if (operators[i][0]==2){
tempMap2.put(operators[i][1],getMaxPriority(tempMap2)+1);//优先级在最大的基础上进行+1
array.add(tempMap1.getOrDefault(operators[i][1],-1));//得到key所对应的value,如果不在就返回-1;
}
}
int a[] = new int[array.size()];
int index = 0;
for(int num :array){
a[index] = num;
++index;
}
return a;
}
public int getMaxPriority(Map<Integer, Integer> tempMap2) {
if(tempMap2.size()==0){
return 0;
}
int value = Integer.MIN_VALUE;
for(int key :tempMap2.keySet()){
if(tempMap2.get(key)>value){
value = tempMap2.get(key);
}
}
return value;
}
public int getMin(Map<Integer,Integer> tempMap2){
int value = Integer.MAX_VALUE ;int keyOfMin=0;
for(int key :tempMap2.keySet()){
if(tempMap2.get(key)<value){
value = tempMap2.get(key);
keyOfMin = key;
}
}
return keyOfMin;
}
} tempMap1存储原来的key以及所对应的value,tempMap2存储key以及所对应的优先级。
1:对operators数组进行遍历,然后对tempMap1与tempMap2进行赋值初始化
/*注:我这里的设置优先级是每次访问一个key的时候最原本的tempMap2所对应的虽大优先级进行+1*/
2:在对tempMap1初始化后,如果operators[i][0]为1的时候我们这个时候需要去判断tempMap1的size(),如果此时大于k的话我们则需要对tempMap2的最小value进行查找,
然后返回最小value所对应的key,然后tempMap1根据key将Map里面存储的数据进行删除
3:operators[i][0]为2的时候,我们首先对tempMap1中key为operators[i][1]的优先级进行+1,然后在tempMap1中查找相关key对应的value,将其放如果到ArrayList中去
最后将ArrayList遍历放到数组中,将数组返回。
4最后时间复杂度o(n),空间复杂度o(n2);
查看12道真题和解析