继续准备面试。这次更新的是和Round Robin很类似的一道题,Short Job First(SJF),最短工作优先。每次换一个工作的时候就看看哪一个工作使用时间最短。
说真的,我看面经的时候差点以为是同一道。
唯一不一样的就是SJF没有quantum的概念,也就是说,不会运行了一段时间,停下来看看有没有已经申请要运行,并且运行时间更短的另一个工作。
最后要求的也是average waiting time。想想如果OA出两道题,一道题是Round Robin,一道是SJF真的是挺愉快的。
下面给出实现代码:
private double WaitAverage(int[] request, int[] duration) {// TODO Auto-generated method stubif(request == null || duration == null || request.length == 0 || duration.length ==0)return 0;int length = request.length;int count = 0;int waitTime = 0;int CurrentTime = 0;int CurP = 0;while(count < length){if(CurP == 0){CurrentTime = duration[0];duration[0] = 0;count++;}else{waitTime += CurrentTime - request[CurP];CurrentTime += duration[CurP];duration[CurP] = 0;count++;}int min = Integer.MAX_VALUE;int remain = 0;for(int i = 0; i < length ; i++){if(duration[i] != 0){remain++;if(request[i] < CurrentTime){if(min > duration[i]){min = duration[i];CurP = i;}}}}if(min == Integer.MAX_VALUE)if(remain>0 && remain < length){for(int i=0; i < length; i++){if(duration[i]!=0){CurP = i;CurrentTime = request[i];break;}}}}return (double)waitTime/(double)length;}
附上我在一亩三分地里面看到的另一个人的代码。总体思路其实差不多,不过看别人的代码总是费脑子的,能看懂一个就好了。而且我的代码是自己手动测试的,有可能会有一些小问题没有查到。
private double findAverage(int[] request, int[] duration) {// TODO Auto-generated method stubif(request == null || duration == null || request.length == 0 || duration.length ==0)return 0;int length = request.length;int[] end = new int[length];int curTime = 0;for(int i=0; i < length; i++){if(i==0){curTime = duration[0];end[0] = duration[0];}else{int minDuration = Integer.MAX_VALUE;int curProcess = 0;for(int j=0; j< length; j++){if(end[j]!= 0)continue;if(request[j] <= curTime){if(duration[j]<minDuration){minDuration = duration[j];curProcess = j;}}else{break;}}if(curProcess == 0 ){curProcess = i;curTime = request[curProcess];}curTime += duration[curProcess];end[curProcess] = curTime;}}int waitsum = 0;for(int i=0; i< length; i++){waitsum +=end[i]-request[i]-duration[i];}return (double)waitsum/(double)length;}