leetcode 621任务调度

leetcode 621任务调度

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.

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.

这个题目给了我们A到Z,26种任务,要求用你的CPU执行,CPU在执行任务时候有个要求,就是相同的两个任务必须间隔为给定的n,就算是空闲着也必须满足n的间距要求。

解题步骤就是:

1.将原来的字符数组按照升序排序,比如["A","A","A","B","B","B","C","C"],就排序为int[26] count = {0, 0, 0, ..., 2, 3, 3};

2.每执行一次周期,就从count数组最后一位往前遍历,如果count[i] 不为空,就count[i] --;表示当前这个任务可以执行了。如果count[i] = 0了,那么就相当于本次时钟周期需要idle,不执行

3.一次时钟周期运行后,执行Arrays.sor(count);让剩余的任务再次以从低到高排序,依次执行

4.以上流程循环,直到执行完成所有任务

比如["A","A","A","B","B","B","C","C"]这个序列任务,给定的相同任务最小间隔为n = 1,则执行如下流程:

先统计升序的字母排序:count = {0, 0, 0, ..., 2, 3, 3}

第一轮:count[25]--,count[24]--

排序剩余字母的数量: {0, 0, 0, ..., 2, 2, 2}

第二轮:count[25]--,count[24]--

排序剩余字母的数量: {0, 0, 0, ..., 1, 1, 2}

第三轮:count[25]--,count[24]--

排序剩余字母的数量: {0, 0, 0, ..., 0, 1, 1}

第四轮:count[25]--,count[24]--

排序剩余字母的数量: {0, 0, 0, ..., 0, 0, 0}

第五轮:没有任务未执行,结束

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值