题目
最近最少使用(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;
}