一個處理器要處理一堆request,一次只能處理一條,如果它有幾個積壓著的requests,它會先執(zhí)行持續(xù)時間短的那個;對于持續(xù)時間相等的requests,先執(zhí)行最早到達(dá)處理器的request。問平均每個request要等多久才能被處理。input:requestTimes[],每個request到達(dá)處理器的時間; durations[] 每個request要處理的持續(xù)時間。 兩個數(shù)組是一一對應(yīng)的,并已按requestTimes[] 從小到大排序過。
Screen Shot 2017-09-13 at 17.09.28.png
import java.util.*;
public class Solution {
static class Process
{
int arrTime;
int exeTime;
public Process(int arrTime, int exeTime)
{
this.arrTime = arrTime;
this.exeTime = exeTime;
}
}
public static double SJL(int[] req, int[] dur)
{
if(req == null || req.length == 0) return 0;
PriorityQueue<Process> queue = new PriorityQueue<>(new Comparator<Process>()
{
@Override
public int compare(Process a, Process b)
{
if(a.exeTime == b.exeTime) return a.arrTime - b.arrTime;
else return a.exeTime - b.exeTime;
}
});
int t = 0, sum = 0, i = 0;
while(i < req.length || !queue.isEmpty())
{
if(queue.isEmpty())
{
queue.offer(new Process(req[i], dur[i]));
t = req[i];
i++;
}
else
{
Process p = queue.poll();
sum += (t - p.arrTime);
t += p.exeTime;
while(i < req.length && req[i] <= t)
{
queue.offer(new Process(req[i], dur[i]));
i++;
}
}
}
return (sum + 0.0) / req.length;
}
public static void main(String[] args)
{
int[] req = {1, 3, 3, 6, 6, 6, 7};
int[] dur = {2 ,2 ,3 ,2, 4, 4, 2};
System.out.println(SJL(req, dur));
}
}