美文网首页
[LeetCode 621] Task Scheduler (M

[LeetCode 621] Task Scheduler (M

作者: 灰睛眼蓝 | 来源:发表于2019-06-25 15:15 被阅读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:

  • The number of tasks is in the range [1, 10000].
  • The integer n is in the range [0, 100].

Solution

  • 与# 358 Rearrange String K Distance Apart一个思路
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;
    }
}

相关文章

网友评论

      本文标题:[LeetCode 621] Task Scheduler (M

      本文链接:https://www.haomeiwen.com/subject/gzotcctx.html