Shortest Job First

一个处理器要处理一堆request,一次只能处理一条,如果它有几个积压着的requests,它会先执行持续时间短的那个;对于持续时间相等的requests,先执行最早到达处理器的request。问平均每个request要等多久才能被处理。input:requestTimes[],每个request到达处理器的时间; durations[] 每个request要处理的持续时间。 两个数组是一一对应的,并已按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));
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,868评论 18 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,121评论 6 13
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,065评论 25 708
  • 先给答案:大多数手机是可以拍到光轨照片的。(昨天答了一道题,今天整理分享出来) 01 首先,我们来分析光轨照片的原...
    朱子先生的摄影思维阅读 27,029评论 20 173
  • 写在前面的话:今天开始写写东西,记录一下光阴。希望自己能坚持,无论是个人感受还是技术讨论。 结点:写在2016已经...
    灵智上人阅读 170评论 0 0