题解 | #设计LRU缓存结构#
设计LRU缓存结构
http://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61
import java.util
import scala.collection.mutable._
object Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* lru design
* @param operators int整型二维数组 the ops
* @param k int整型 the k
* @return int整型一维数组
*/
def LRU(operators: Array[Array[Int]],k: Int): Array[Int] = {
// write code here
val output = new ArrayBufferInt
var i = 0
var map = new util.LinkedHashMapString,Int
while(i < operators.length){
val item = operators(i)
if(item(0)==1){//set
SetupdateMap(map,item(1).toString,item(2),k)
}else if(item(0)==2){//get
val result = GetetupdateMap(map,item(1).toString)
output.append(result)
}
i=i+1
}
output.toArray
}
def GetetupdateMap(map:util.LinkedHashMap[String,Int], key:String):Int={
val output = if(map.containsKey(key)){
val value = map.get(key) //自动更新后该key放在最后一个
map.remove(key)
map.put(key,value) //更新后该key放在第一个位置
value
}else{
-1
}
output
}
def SetupdateMap(map:util.LinkedHashMap[String,Int], key:String, value:Int, K:Int):Unit={
if (map.containsKey(key)){
map.put(key,value)
}else{
if(map.size()<K){
map.put(key,value)
}else{
val keysiterator = map.keySet().iterator()
var lastkey = keysiterator.next()
map.remove(lastkey)
map.put(key,value)
}
}
}
}