/**
* Created by Bruce on 2017/6/15.
*/
/**
* Input:array = [1,2,3,5,8,4,5,2,9], size = 4
* Output: result = 8
* LRU分析参考:
* ⑴get(key):如果key在cache中,则返回对应的value值,否则返回-1
* ⑵set(key,value):如果key不在cache中,则将该(key,value)插入cache中
* (注意,如果cache已满,则必须把最近最久未使用的元素从cache中删除);如果key在cache中,则重置value的值。
* cacheQqueue in 缺页数
* 1,2,3,5 8 4
* 2,3,5,8 4 5
* 3,5,8,4 5 6
* 3,5,8,4 2 6
* 5,8,4,2 9 7
* 8,4,2,9 8
*
*/
object page extends App{
def lru(list:List[Int],q:Int):Int= {
var count = 0 //统计缺页数
val listCache = scala.collection.mutable.ListBuffer[Int]() //声明一个可变list集合用作缓存
for(a <- list){
//如果缓存中不存在该元素,则将该元素放到缓存队列中(如果list中的元素个数超过缓存大小,则移除list.head)
if(!listCache.exists(c => c==a)){
listCache += a
count +=1
if(listCache.length>=q)
listCache-=listCache.head
}
}
return count
}
println(lru(List(1,2,3,5,8,4,5,2,9),4))
}
Scala的LRU算法实现
最新推荐文章于 2024-03-30 15:37:29 发布