Lintcode:945 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.

个人思路:首先分别找出每个字母出现的次数,此时采用的贪心策略就是先安排次数多的进cpu(即次数最多的字母放在interval两边,其他字母放interval之中),这样就满足题目的n要求,因为写的代码过于丑陋,只记录大神的代码

dalao思路:找到第一个次多次数的字母,(n+1)代表interval和边界上的数,25-i代表如果在几个interval中没有安排外多出现在尾巴的数(感觉不太算是贪心策略,而更多像观察数学规律)

 public int leastInterval(char[] tasks, int n) {
        // write your code here
        int[] c = new int[26];
        for(char t : tasks){
            //System.out.print(t + " ");
            c[t - 'A']++;
        }
        Arrays.sort(c);
        int i = 25;
        while(i >= 0 && c[i] == c[25]) {
            i--;
        }

        return Math.max(tasks.length, (c[25] - 1) * (n + 1) + 25 - i);        
    }

summary:涉及到字母出现次数的,使用int[] c = new int[26]; for(char t : tasks){ //System.out.print(t + " "); c[t - 'A']++;,既方便又快

猜你喜欢

转载自blog.csdn.net/qq_38702697/article/details/82819045