Tuesday, May 22, 2018

621 Task Scheduler

621Task Scheduler
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.
Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].
------------------------
Solution #1, 数empty slots。Leetcode上有讲解
复杂度是O(n), n等于task的数量
另一种类似方法是计算相同最大出现次数元素的个数。[A3,B3,C1,D1], 个数为2,A和B。
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 maxCount = map[25] - 1;
        int slots = maxCount * n;
        for (int i = 24; i >= 0; i--) {
            slots -= Math.min(maxCount, map[i]);
        }
        
        if (slots > 0) {
            return slots + tasks.length;
        }
        return tasks.length;
    }
}

Solution#2,priority queue
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 i : map) {
            queue.add(i);
        }
        
        int top = queue.poll();
        int count = top;
        for (int i = 0; i < top - 1; i++) {
            List<Integer> hold = new ArrayList<>();
            int index = 0;
            while (index < n && !queue.isEmpty()) {
                int pop = queue.poll() - 1;
                if (pop > 0) {
                    hold.add(pop);
                }
                
                index++;
                count++;
            }
            count += n - index;
            
            for (int j : hold) {
                queue.add(j);
            }
        }
        
        while (!queue.isEmpty()) {
            count += queue.poll();
        }
        
        return count;
    }
}

No comments:

Post a Comment