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 intervaln that means between twosame 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.

Example 1:

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

Note:

  1. The number of tasks is in the range [1, 10000].
  2. The integer n is in the range [0, 100].

题意

关键:模拟CPU任务分配,A 到 Z表示不同的任务,任务可以以不同顺序进行。每个任务可以在一个时间间隔中完成。对于一个时间间隔,CPU可以执行一个任务或者是闲置。但是,两个同样的任务之间需要有 n 个冷却时间,也就是说假如A执行后,那么未来n个时间间隔内,A是不允许再执行的。

说明

该问题可以看做区间找点问题的扩展,只不过可让区间进行扩展


分析及解答


解法1:【贪心 + 数学表达】

  • 贪心算法】角度的选择很重要。作者在这里采取了分块的形式,按照出现频率最多(假设频率为k)的将其分为了k块,然后每一轮向这k个区间个插入1个。如何选择贪心策略
  • 数学公式表达】通过数学公式明确考虑问题的角度,清晰表达解答问题的思路,明确其中涉及的变量以及变量函数间的关系。
  • 证明贪心有效性】如何证明一个贪心策略是能够解决一个问题的?

来自:concise Java Solution O(N) time O(26) space

扫描二维码关注公众号,回复: 69154 查看本文章

[java]  view plain  copy
  1. // (c[25] - 1) * (n + 1) + 25 - i  is frame size  
  2. // when inserting chars, the frame might be "burst", then tasks.length takes precedence  
  3. // when 25 - i > n, the frame is already full at construction, the following is still valid.  
  4. public class Solution {  
  5.     public int leastInterval(char[] tasks, int n) {  
  6.   
  7.         int[] c = new int[26];  
  8.         for(char t : tasks){  
  9.             c[t - 'A']++;  
  10.         }  
  11.         Arrays.sort(c);  
  12.         int i = 25;  
  13.         while(i >= 0 && c[i] == c[25]) i--;  
  14.   
  15.         return Math.max(tasks.length, (c[25] - 1) * (n + 1) + 25 - i);  
  16.     }  
  17. }  

关于上面说法的说明:

  • 分块】依据出现最多的任务(假如是A)进行分块.
  • 问题规约】按照任务从多到少依次为每个块分配任务。我们这里假定,A一定能够符合距离下一个A的冷却时间为n,那么跟在A后面的也一定符合。只要保证A符合就行了,其他任务的的符合要求都可以由A的符合推导出来。

猜你喜欢

转载自blog.csdn.net/momo_mo520/article/details/80069369