FIFO页面置换算法实现(百度笔试题1)

来源:互联网 发布:网络大电影发行 编辑:程序博客网 时间:2024/06/05 05:27

第一次百度笔试,题目不难,但由于一些地方没有注意,导致通过用例出现问题,现进行整理,吸取教训,从哪里跌倒从哪里爬起来!!!

FIFO页面置换算法:

一个函数,两个参数

public static int countCacheMiss(int max_cache_size, int[] page_requests){}

max_cache_size:代表缓冲区个数

page_requests:代表请求页面号数组

要求,实现FIFO页面替换算法(缓冲区满并缺页时,替换掉占据时间最长的页面),输出缺页次数

用例:

2

1  2  1  3  1  2

输出:5


2

2  3  1  3  2  1  4  3  2

输出:7

// IMPORT LIBRARY PACKAGES NEEDED BY YOUR PROGRAM// SOME CLASSES WITHIN A PACKAGE MAY BE RESTRICTED// DEFINE ANY CLASS AND METHOD NEEDED// CLASS BEGINS, THIS CLASS IS REQUIREDpublic class baidu1{  // METHOD SIGNATURE BEGINS, THIS METHOD IS REQUIRED  public static int countCacheMiss(int max_cache_size, int[] page_requests)  {      int count=0;//缺页次数      int []hit=new int[50];//缓冲区持续(未换页)时长      int []content=new int[50];       int k;      for(int t=0;t<max_cache_size;t++){          content[t]=-1;//-1代表该缓冲区为空      }      for(int i=0;i<page_requests.length;i++){         if((k=find(max_cache_size,content,page_requests[i]))!=-1){             continue;//当页面在chche中找到后,所有的持续时间加1,因此这里可以都不加         }else{             int j=0;             for(;j<max_cache_size;j++){                 if(content[j]==-1){//判断是否有空chche                     content[j]=page_requests[i];                     count++;                     hit[j]=1;                     break;                             }             }                 if(j==max_cache_size){              int max=0;              for(int h1=0;h1<max_cache_size;h1++){//找持续时间最大的cache位置                    if(hit[h1]>hit[max]){                     max=h1;                  }               }              content[max]=page_requests[i];              count++;              hit[max]=1;              for(int h2=0;h2<max_cache_size;h2++){                  if(h2!=max){                   hit[h2]++;                 }                }             }         }        /*  for(int t1=0;t1<max_cache_size;t1++){            System.out.print(content[t1]+" ");         }         System.out.println();        */            }      return count;  }    public static int find(int k,int content[],int value){//判断页面是否已在缓冲区中,在则返回缓冲区编号        for(int j=0;j<k;j++){            if(content[j]==value){                return j;            }        }        return -1;    }  // METHOD SIGNATURE ENDS    public static void main(String[]args){    int []A1={2,3,1,3,2,1,4,3,2};    int[]A2={1,2,1,3,1,2};    int max_cache_size=2;   System.out.println(countCacheMiss(max_cache_size,A1));    }}


0 0
原创粉丝点击