力扣练习之任务调度器

我爱海鲸 2023-05-29 22:38:43 暂无标签

简介中级算法、其他、Rust

原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-medium/xwvaot/

解法一(python)

class Solution:
    def leastInterval(self, tasks: List[str], n: int) -> int:
        counts = Counter(tasks)
        max_count = max(counts.values())
        ans = (max_count - 1) * (n + 1) + sum(1 for count in counts.values() if count == max_count)
        return max(ans, len(tasks))

解法二(Rust)

use std::collections::HashMap;

impl Solution {
    pub fn least_interval(tasks: Vec<char>, n: i32) -> i32 {
        let mut counts = HashMap::new();
        let mut max_count = 0;
        for task in &tasks {
            let count = counts.entry(task).or_insert(0);
            *count += 1;
            max_count = max_count.max(*count);
        }

        let mut ans = (max_count - 1) * (n + 1) as usize;
        for (_, count) in counts {
            if count == max_count {
                ans += 1;
            }
        }

        ans.max(tasks.len() as usize) as i32
    }
}

思路:

贪心的思路来解决这个问题。我们首先可以统计每个任务出现的次数,并找出出现次数最多的任务个数 max_count。那么完成所有任务的最短时间就是:(max_count - 1) * (n + 1) + 相同出现次数的任务个数。

计算过程解释一下,完成所有任务需要的时间至少为 max_count - 1,因为最后一个任务不需要等待冷却时间。在执行出现次数最多的任务时,需要等待 (max_count - 1) * n 个单位时间才能执行下一个这种任务或者待命。此时,除了出现次数最多的任务以外,还有相同出现次数的任务需要执行,因此我们将相同出现次数的任务个数加上即可。

我们使用 Counter 类统计每个任务出现的次数,并找出出现次数最多的任务个数 max_count。然后按照上面的计算过程计算最短时间。注意,需要用 max 函数将计算出的时间和任务列表长度取一个较大的值,这是因为任务列表可能很短,而计算出来的时间可能会比任务列表还要短。

你好:我的2025