最近最少使用(LRU)算法模拟--LeastRecentPage
2016-07-04 17:25
681 查看
题目
最近最少使用(LRU)缓存算法从缓存中收回最近最少使用元素(当缓存满时)。当缓存请求元素后,应将元素添加到缓存(如果之前不再缓存中),并将其作为缓存中最近使用最多的元素。给高速缓存的最大容量和一个整数(向缓存发出请求),请使用LRU高速缓存算法计算高速缓存请求失败的次数。当请求的整数不在高速缓存中时,说明高速缓存请求失败。
初始状态下告诉缓存是空的。
编写程序模拟LRU的运行过程,
依次输入分配给某进程的缓存大小(页帧数)和该进程访问页面的次序,用-1作为输入结束标志,
初始时缓存为空,要求输出使用LRU算法的缺页次数
测试用例
TestCase 1:Input:
4
4 3 2 1 4 3 5 4 3 2 1 5 4 -1
Expected Return Value:
9
TestCase 2:
Input:
3
1 2 3 3 2 1 4 3 2 1 -1
Expected Return Value:
7
TestCase 3:
3
Input:
3 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 -1
Expected Return Value:
11
TestCase 4:
2
Input:
2 3 1 3 2 1 4 3 2-1
Expected Return Value:
8
代码
import java.util.Scanner;public class LeastRecentPage {
public static final int MAX_TASK_NUM = 100;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
while (scan.hasNext()) {
int cacheBlocks = scan.nextInt();
int[] taskPages = new int[MAX_TASK_NUM];
int i = 0;
int page = scan.nextInt();
while (page != -1) // 输入结束标志
{
taskPages[i++] = page;
page = scan.nextInt();
}
System.out.println(LRU.calMissingPages(cacheBlocks, i, taskPages));
}
scan.close();
}
}
class LRU {
public static int calMissingPages(int cacheBlocks, int taskNum, int taskPages[]) {
int[] cache = new int[cacheBlocks]; // 缓存
cache[0] = taskPages[0]; // 预处理,先将第一个作业页面放入缓存
int cachePages = 1; // 已缓存的页面数
int missingNum = 1; // 缺页次数
boolean missingFlag;// 缺页标志
for (int i = 1; i < taskNum; i++) {
missingFlag = true;
for (int j = 0; j < cachePages; j++) {
if (cache[j] == taskPages[i]) // 命中
{
missingFlag = false;
int t = cache[j];
// 插入排序将当前命中的元素移到队尾
for (int k = j + 1; k < cachePages; k++)
cache[k - 1] = cache[k];
cache[cachePages - 1] = t;
break;
}
}
if (missingFlag)// 未命中
{
missingNum++;
if (cachePages == cacheBlocks) // 缓存已满
{
for (int k = 1; k < cachePages; k++)
cache[k - 1] = cache[k];
cache[cachePages - 1] = taskPages[i];
} else // 缓存未满
{
cache[cachePages] = taskPages[i];
cachePages++;
}
}
}
return missingNum;
}
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法