[Leetcode] 621 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.
Links: https://leetcode.com/problems/task-scheduler/

解题思路

我是参考这位的 https://leetcode.com/problems/task-scheduler/discuss/104496/concise-Java-Solution-O(N)-time-O(26)-space
我只想说,真厉害。不仅有方法,还有证明。希望哪天我也能和这位大佬一样。

解题代码

我用python重新写了一遍

class Solution(object):
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        c = [0 for i in range(26)]
        for item in tasks:
            c[ord(item) - ord('A')] += 1
        c.sort()
        i = 25
        while(i >= 0 and c[i] == c[25]):
            i = i - 1
        #print(i, c)
        return max(len(tasks), (c[25]-1)*(n+1)+25-i

这里有几点需要注意:

  • Python 里面字符相减需要用ord()函数,比如 ‘B’ - ‘A’,这样会报错。需要写为ord(‘B’) - ord(‘A’)
  • 对最后一句的理解 max(len(tasks), (c[25]-1)*(n+1)+25-i
    这里有两种情况:
    – tasks不需要插入空余的等待,结果是len(tasks)
    – 需要插入等待,这个时候把出现频率最大的一个或者几个字符绑定在一起,举几个例子(copy别人的):
    1. AAAABBBEEFFGG 3
      出现最多的是A,以A为基准,凑成AXXXAXXXAXXXA,再进行下一步操作,插入其余字符。
    2. ACCCEEE 2
      出现最多的是C和E,以它们为组合,凑成CEXCEXCE,再插入其余字符。
      这种情况下 (c[25] - 1)*(n+1)是很好理解的,剩下的25-i,就是有几个元素捆绑在一起了,要加上去,因为最后一个捆绑的组合是不需要插入空余等待时间的。

Aufwiedersehen

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值