Loading

Leetcode621.任务调度

题目:https://leetcode-cn.com/problems/task-scheduler/submissions/

官方题解:任务调度器

代码:

class Solution {
    public int leastInterval(char[] tasks, int n) {
        char[] map = new char[26];
        for(char c : tasks){
            map[c - 'A'] ++;//记录字母出现次数
        }
        PriorityQueue<NewChar> priority = new PriorityQueue<>((a, b) -> b.cnt - a.cnt);//用极大堆保存字母及出现次数
        for(int i=0; i<26; i++){
            if(map[i] != 0){
                priority.offer(new NewChar((char)('A' + i), map[i]));
            }
        }
        // 先安排最大出现次数,两个相同的字符中间空n个空位
        NewChar t = priority.peek();
        char[] res = new char[t.cnt * (1 + n)];
        int start = 0;
        while((t = priority.poll()) != null){
            while(start < res.length && res[start]!='\0') ++start;
            int index = start;
            for(int i=0; i<t.cnt; index+=(n+1), ++i){
                if(index >= res.length) return tasks.length; // 当索引超出限制时,说明该任务安排不超过任务数,解析见官方题解
                res[index]= t.val;
            }
        }
        int len = res.length;
        while(res[--len] == '\0') ;
        return len + 1;
    }

    class NewChar{
        char val;
        int cnt;
        public NewChar(char val, int cnt){this.val = val; this.cnt = cnt;}
    }
}

 

posted @ 2020-12-05 15:24  yoyuLiu  阅读(129)  评论(0编辑  收藏  举报