|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * 621. Task Scheduler |
| 7 | + * |
| 8 | + * Given a char array representing tasks CPU need to do. |
| 9 | + * It contains capital letters A to Z where different letters represent different tasks. |
| 10 | + * Tasks could be done without original order. |
| 11 | + * Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. |
| 12 | + * However, there is a non-negative cooling interval n that means between two same tasks, |
| 13 | + * there must be at least n intervals that CPU are doing different tasks or just be idle. |
| 14 | + * You need to return the least number of intervals the CPU will take to finish all the given tasks. |
| 15 | +
|
| 16 | + Example 1: |
| 17 | + Input: tasks = ['A','A','A','B','B','B'], n = 2 |
| 18 | + Output: 8 |
| 19 | + Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. |
| 20 | +
|
| 21 | + Note: |
| 22 | + The number of tasks is in the range [1, 10000]. |
| 23 | + The integer n is in the range [0, 100]. |
| 24 | + */ |
| 25 | +public class _621 { |
| 26 | + |
| 27 | + /**Could be simplified just using an array to record the frequencies of each letter, like this one: |
| 28 | + * https://leetcode.com/articles/task-scheduler/#approach-2-using-priority-queue-accepted*/ |
| 29 | + public int leastInterval(char[] tasks, int n) { |
| 30 | + Map<Character, Integer> map = new HashMap<>(); |
| 31 | + for (char c : tasks) { |
| 32 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 33 | + } |
| 34 | + PriorityQueue<Task> maxHeap = new PriorityQueue<>((a, b) -> b.total - a.total); |
| 35 | + for (Map.Entry<Character, Integer> entry : map.entrySet()) { |
| 36 | + maxHeap.offer(new Task(entry.getValue(), entry.getKey())); |
| 37 | + } |
| 38 | + int times = 0; |
| 39 | + while (!maxHeap.isEmpty()) { |
| 40 | + int i = 0; |
| 41 | + List<Task> temp = new ArrayList<>(); |
| 42 | + while (i <= n) { |
| 43 | + if (!maxHeap.isEmpty()) { |
| 44 | + if (maxHeap.peek().total > 1) { |
| 45 | + Task curr = maxHeap.poll(); |
| 46 | + temp.add(new Task(curr.total-1, curr.character)); |
| 47 | + } else { |
| 48 | + maxHeap.poll(); |
| 49 | + } |
| 50 | + } |
| 51 | + times++; |
| 52 | + if (maxHeap.isEmpty() && temp.size() == 0) break; |
| 53 | + i++; |
| 54 | + } |
| 55 | + for (Task task : temp) { |
| 56 | + maxHeap.offer(task); |
| 57 | + } |
| 58 | + } |
| 59 | + return times; |
| 60 | + } |
| 61 | + |
| 62 | + class Task { |
| 63 | + int total; |
| 64 | + char character; |
| 65 | + public Task(int total, char character) { |
| 66 | + this.total = total; |
| 67 | + this.character = character; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments