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']++;,既方便又快

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值