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:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Note:
The number of tasks is in the range [1, 10000].
The integer n is in the range [0, 100].
Solution1
- Simulate the whole process using heap, but low efficiency and large space consuming
- For character counting task, consider using integer array first rather than map
- Collections.reverseOrder() returns a comparator sorting in reverse order
- Outer loop is used to go through each character is heap; Inner loop indicates that for each n intervals, arrange the top appear times character and store them into a temporary list that it can not be used again in this interval.
- Beats 32% submissions
Complexity Analysis
- Time complexity : O(n). We iterate over tasks array only once. (O(n)). Sorting tasks array of length n takes O(26log(26))= O(1) time. After this, only one iteration over 26 elements of map is done O(1).
- Space complexity : O(1). map array of constant size(26) is used.
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
for (char c: tasks)
map[c - 'A']++;
PriorityQueue < Integer > queue = new PriorityQueue < > (26, Collections.reverseOrder());
for (int f: map) {
if (f > 0)
queue.add(f);
}
int time = 0;
while (!queue.isEmpty()) {
int i = 0;
List < Integer > temp = new ArrayList < > ();
while (i <= n) {
if (!queue.isEmpty()) {
if (queue.peek() > 1)
temp.add(queue.poll() - 1);
else
queue.poll();
}
time++;
if (queue.isEmpty() && temp.size() == 0)
break;
i++;
}
for (int l: temp)
queue.add(l);
}
return time;
}
}
Solution2
- Beats 100% submissions
Complexity Analysis
- Time complexity : O(1).
- Space complexity : O(1).
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] map = new int[26];
for (char c: tasks)
map[c - 'A']++;
Arrays.sort(map);
int max_val = map[25] - 1, idle_slots = max_val * n;
for (int i = 24; i >= 0 && map[i] > 0; i--) {
idle_slots -= Math.min(map[i], max_val);
}
return idle_slots > 0 ? idle_slots + tasks.length : tasks.length;
}
}
网友评论