Leetcode:621. Task 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].

題目分析:給定任務序列,要求同名任務必須間隔n,中間可以處於空閒,問任務序列最短需要多長時間完成。
分析:求出最少需要處於空閒的個數,然後加上任務總數即爲所求。而要想使得最小處於空閒個數,可以這樣處理:按照同名任務數降序排列,首先將最多同名任務數的任務(假設爲A)間隔n排列,然後將次多的任務(假設爲B)從第二個位置間隔n放置,依次下去填入A的間隔裏面。在依次進行的過程中可能會出現A中間的空位置(n)已經填滿,那麼可以將還未安排的任務直接插A間隔中,此時並不會增加ideal的個數。
例如: A 4; B 3; C 2;n=2。依次排列如下:
1)A/ / /A/ / /A/ / /A
2)A/B/ /A/B/ /A/B/ /A
3)A/B/C/A/B/C/A/B/ /A
因此必然多出來1個ideal位置,所以最短時間是1+4+3+2=10.
再如:A 4; B 3; C 2;D 2;E 1;n=2。依次排列如下:
1)A/ / /A/ / /A/ / /A
2)A/B/ /A/B/ /A/B/ /A
3)A/B/C/A/B/C/A/B/ /A
4)A/B/C/A/B/C/A/B/D/A
5)A/B/C/D/A/B/C/A/B/D/A
6)A/B/C/D/A/B/C/E/A/B/D/A
因此必然多出來0個ideal位置,所以最短時間是4+3+2+2+1=12。
代碼如下:

class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] count=new int[26];
        for(int i=0;i<tasks.length;i++)
            count[tasks[i]-'A']++;
        int max=0;
        for(int i=0;i<26;i++)
            if(count[i]>max)
                max=count[i];
        int otherC=0;
        int maxC=0;
        for(int i=0;i<26;i++)
        {
            if(count[i]==max)
                maxC++;
            if(count[i]>0)
            {
                otherC+=(count[i]==max?max-1:count[i]);
            }
        }  
        otherC-=max-1;
        if(maxC>n)
            return tasks.length;
        int temp=(max-1)*n-otherC;
        temp=temp<0?0:temp;
        return tasks.length+temp;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章