[LeetCode 621] Task Scheduler (M

2019-06-25  本文已影响0人  灰睛眼蓝

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:

Solution

class Solution {
    public int leastInterval(char[] tasks, int n) {
        if (tasks == null || tasks.length == 0)
            return 0;
        
        List<String> result = new ArrayList<> ();
        
        int[] frequency = new int[26];
        int[] invalidIndex = new int[26];
        Set<Character> allTasks = new HashSet<> ();
        
        for (int i = 0; i < tasks.length; i++) {
            frequency [tasks[i] - 'A']++;
            allTasks.add (tasks[i]);
        }
        
        while (allTasks.size () != 0) {
            int index = result.size ();
            int nextLetterPos = getNextLetterPos (frequency, invalidIndex, index);
            
            if (nextLetterPos == -1) {
                result.add ("Idle");
            } else {
                result.add (String.valueOf ((char) (nextLetterPos + 'A')));
                frequency[nextLetterPos]--;
                invalidIndex[nextLetterPos] += n + 1;
                
                if (frequency[nextLetterPos] == 0) {
                    allTasks.remove ((char) (nextLetterPos + 'A'));
                }
            }
        }
        
        System.out.println (Arrays.toString (result.toArray ()));
        return result.size ();
    }
    
    public int getNextLetterPos (int[] frequency, int[] invalidIndex, int index) {
        int maxPriority = -1;
        int pos = -1;
        
        for (int i = 0; i < frequency.length; i++) {
            if (frequency[i] > 0 && frequency[i] >= maxPriority && index >= invalidIndex[i]) {
                maxPriority = frequency[i];
                pos = i;
            }
        }
        
        return pos;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读