Leetcode 621. Task Scheduler

本文介绍了一种解决CPU任务调度问题的算法,通过使用哈希表和优先队列,确保了在给定冷却间隔的情况下,CPU能以最少的时间完成所有任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example 1:

Input: tasks = ['A','A','A','B','B','B'], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

我们要用一个hashmap 来储存 每个字符和出现次数的映射关系,priority queue 来记录出现次数。

n = 2 是, 每次都是 3个 3个 地出现,所以cycle 是 3. 如果 pq 不为 空, 把 pq 最大的 n 个加入到pq 中,同时worktime 加一, 再把 每个 - 1 加回到pq 里。pq 还有书的话,则要加上 一个 cycle, 反之只用加上 worktime。

public int leastInterval(char[] tasks, int n) {        
        Map<Character, Integer> map = new HashMap<>();
        for (char t : tasks) map.put(t, map.getOrDefault(t, 0) + 1);
        Queue<Integer> pq = new PriorityQueue<>((a, b) -> b - a);
        pq.addAll(map.values());
        int res = 0;
        int cycle = n + 1;
        while (!pq.isEmpty()) {
            int worktime = 0;
            List<Integer> tmp = new ArrayList<>();
            for (int i = 0; i < cycle; i++) {
                if (!pq.isEmpty()) {
                    tmp.add(pq.poll());
                    worktime++;
                }
            }
            for (int cnt : tmp) {
                if (--cnt > 0) pq.offer(cnt);
            }
            res += !pq.isEmpty() ? cycle : worktime;
        }
        return res;
    }








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值