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

分析

  1. initialize an interger array named map, length of 26 inorder to remark frequency of every letter

  2. traverse the whole char array ; remark frequency of every letter

  3. find the max value in map

  4. 解题

class Solution {
    public int leastInterval(char[] tasks, int n) {
        // base case
        if(tasks.length == 0 ) return 0;

        int []map = new int[26];

        //标记
        for(int i = 0; i< tasks.length; i++){
            map[tasks[i]-'A']++;
        }

        int max = 0;
        int c = 0;

        //找到频率最高的
        for(int i = 0; i< 26; i++){
            max = Math.max(max, map[i]);
        }

        //频率最高的可能被安排到最后
         for(int i = 0; i< 26; i++){
            if(max==map[i]){
                c++;
            }
        }

        int ans = (n+1) * (max-1) + c;
        return Math.max(tasks.length, ans);     
    }
}

results matching ""

    No results matching ""