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].

       這道題目的意思是:CPU在進行任務調度是,如果設置間隔爲n,則相同的任務之間的間隔是n,如果所有的任務不夠間隔n次出現,

就用idle表示,即讓CPU空轉。用大寫字母從A-Z表示不同的任務,求出完成所有的任務調度的間隔數。

分析如下:首先統計每個任務出現的次數,因爲任務的出現必須間隔n個,把CPU的每輪調度有n+1個,完整的調度有max-1輪,max爲出現次數最多的

任務個數,然後剩下的最後一輪調度是前面max-1輪調度剩下的任務的個數,只需要統計出現次數最多的任務個數即可。代碼中對數組a排序後,

max=a[25],25-i爲出現次數最多的任務個數。但是如果經過這些調度後仍然有漏掉的任務,可以用Math.max(tasks.length,(a[25]-1)*(n+1)+25-i))

解決這個問題。代碼如下:

int [] a = new int[26];
    	for(char t:tasks){a[t-'A']++;}
    	Arrays.sort(a);
    	int i=25;
    	while(i>=0&&a[i]==a[25]){i--;}
    	return(Math.max(tasks.length, (a[25]-1)*(n+1)+25-i));



發佈了64 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章