November 24, 2019

621. Task Scheduler

621. Task Scheduler

Greedy 解法,参加花花酱的讲解视频. Time = O(n), space = O(1).

class Solution {
    public int leastInterval(char[] tasks, int n) {
        int[] count = new int[26];
        for (char c : tasks) {
            count[c - 'A']++;
        }
        int maxCount = 0;
        for (int i = 0; i < 26; i++) {
            maxCount = Math.max(maxCount, count[i]); 
        }
        int total = (maxCount - 1) * (n + 1); // 前n-1个interval最长长度
        int last = 0;
        for (int i = 0; i < 26; i++) {
            if (count[i] == maxCount) {
                last ++; // 第n个interval长度
            }
        }
        return Math.max(total + last, tasks.length); 
    }
}
comments powered by Disqus