zoukankan      html  css  js  c++  java
  • a_lc_找到处理最多请求的服务器(treemap+treeset)

    服务器不能同时处理超过一个请求,1~k这些服务器顺序接受请求;
    若k个服务器都在处理请求,那么新来的请求会被扔掉,否则,谁空闲就轮到谁接;
    问接受请求最多的服务器时哪个

    思路

    • set维护当前空闲服务器列表free(按id升序排列)
    • map/pq(这里用treemap)维护存每个时间点对应的所有服务器列表,当请求arrival[i]到来时,我就去map中找运行时间在arrival[i]及之前结束的服务器列表,将他们全部add到set中,归为空闲服务器
    class Solution {
        public List<Integer> busiestServers(int k, int[] arrival, int[] load) {
            int n=load.length, max=0, cnt[] = new int[k];
            TreeMap<Integer, List<Integer>> tmap = new TreeMap<Integer, List<Integer>>();
            TreeSet<Integer> free = new TreeSet<>();
            for (int i=0; i<k; i++) free.add(i);
    
            for (int i=0; i<n; i++) {
                var map = tmap.headMap(arrival[i], true); //找到小于等于当前请求到达时间就空闲的所有服务器
                var it = map.entrySet().iterator();
                while (it.hasNext()) {
                    var data = it.next();
                    free.addAll(data.getValue());
                    it.remove();
                }
                if (free.isEmpty()) continue;
                Integer id = i%k, candidate = free.ceiling(id); //找到≥id的最小服务器编号
                if (candidate==null) candidate = free.first(); //如果free不空但找不到,证明当前id是最大的编号
                tmap.computeIfAbsent(arrival[i]+load[i], v->new LinkedList<>()).add(candidate);
                free.remove(candidate);
                cnt[candidate]++;
                if (cnt[candidate]>max) max = cnt[candidate];
            }
            LinkedList<Integer> ans = new LinkedList<Integer>();
            for (int i=0; i<k; i++) if (cnt[i]==max)
                ans.add(i);
            return ans;
        }
    }
    
  • 相关阅读:
    JavaScript中需要注意的几个问题
    前端编码规范之JavaScript
    那些年,我们一起玩过的响应式布局
    前端编码规范之CSS
    一个不陌生的JS效果-marquee,用css3来实现
    解读jQuery中extend函数
    字体大小自适应纯css解决方案
    浅谈叶小钗面试的几个问题
    【Python开发】C和Python之间的接口实现
    【Python开发】【编程开发】各种系统的清屏操作命令
  • 原文地址:https://www.cnblogs.com/wdt1/p/13766555.html
Copyright © 2011-2022 走看看