Leetcode 621. Task Scheduler
来源:互联网 发布:linux for qq2016安装 编辑:程序博客网 时间:2024/06/07 03:01
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 = 2Output: 8Explanation: 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; }
- LeetCode 621. Task Scheduler
- 【LeetCode】621. Task Scheduler
- [LeetCode] 621. Task Scheduler
- Leetcode 621. Task Scheduler
- [leetcode]621. Task Scheduler
- leetcode 621. Task Scheduler
- Leetcode:621. Task Scheduler
- [LeetCode]621. Task Scheduler
- leetcode 621. Task Scheduler
- Leetcode 621. Task Scheduler
- leetcode 621. Task Scheduler
- leetcode 621. Task Scheduler (贪心)
- leetcode 621 Task Scheduler
- [Leetcode 621] Task Scheduler
- [leetcode] 621 Task Scheduler
- LeetCode Task Scheduler
- LeetCode-Task Scheduler
- LeetCode:Task Scheduler
- 2017暑假集训 div1 匹配问题(1)
- 构建 RESTful Web 服务
- Activity四种启动模式
- Firefox浏览器自带"阻止此页面创建其它对话框"设置为不显示
- Redis 2.8 配置文件说明
- Leetcode 621. Task Scheduler
- Retrofit注解详解以及Builder参数详解
- ExecutorService详解
- Oracle PLsql table用法
- hadoop面试常见问题及相关总结
- 动手实操 | 如何用 Python 实现人脸识别,证明这个杨幂是那个杨幂?
- 基于Netty和Zookeeper实现RPC框架
- Android Matrix使用总结
- iOS 设定UIButton 按钮圆角:纯代码方法 和 storyboard中设定