Number of concurrent tasks

本文介绍了一个简单的设计方案,用于记录和统计并发进程的数量。通过维护一个时间点到进程变化数量映射的数据结构,该方案能够高效地查询任意给定时间点上的活跃进程数。

一堆log有开始和结束点,每个log相当于一个进程。

design一个东西可以支持输入一个时间点,返回这个时间点有多少个进程在跑。


跟leetcode 732 My Calendar III 一个意思。


class Concurrent {
    
    private TreeMap<Integer, Integer> times = new TreeMap<>();
    
    public void book(int s, int e) {
        times.put(s, times.getOrDefault(s, 0) + 1); 
        times.put(e, times.getOrDefault(e, 0) - 1);   
    }
    
    public int getConcurrent(int s){
        int res = 0;
        for(int key : times.keySet()){
            if(key <= s){
                res += times.get(key);
            }
        }
         
        return res;
    }
      
    public static void main(String[] args) {
        Concurrent my = new Concurrent();
        my.book(1,2);
        my.book(1,3);
        my.book(2,4);
        int res = my.getConcurrent(3);    
        System.out.println(res);     
    }
       
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值