621. 任务调度器(时间模拟)

package com.heu.wsq.leetcode;

import java.util.*;

/**
 * 621. 任务调度器
 * @author wsq
 * @date 2020/12/5
 * 给你一个用字符数组 tasks 表示的 CPU 需要执行的任务列表。其中每个字母表示一种不同种类的任务。任务可以以任意顺序执行,并且每个任务都可以在 1 个单位时间内执行完。在任何一个单位时间,CPU 可以完成一个任务,或者处于待命状态。
 *
 * 然而,两个 相同种类 的任务之间必须有长度为整数 n 的冷却时间,因此至少有连续 n 个单位时间内 CPU 在执行不同的任务,或者在待命状态。
 *
 * 你需要计算完成所有任务所需要的 最短时间 。
 *
 *  
 *
 * 示例 1:
 *
 * 输入:tasks = ["A","A","A","B","B","B"], n = 2
 * 输出:8
 * 解释:A -> B -> (待命) -> A -> B -> (待命) -> A -> B
 *      在本示例中,两个相同类型任务之间必须间隔长度为 n = 2 的冷却时间,而执行一个任务只需要一个单位时间,所以中间出现了(待命)状态。
 *
 * 链接:https://leetcode-cn.com/problems/task-scheduler
 */
public class TaskScheduler {
    /**
     * 采用时间模拟的方法,在对应时刻选取当前 "能够执行的" 并且 "剩余数量最大的"
     * @param tasks
     * @param n
     * @return
     */
    public int leastInterval(char[] tasks, int n) {
        // 统计每个任务的个数
        Map<Character, Integer> map = new HashMap<>();
        for (char task : tasks) {
            map.put(task, map.getOrDefault(task, 0) + 1);
        }
        // 使用两个列表存储任务的最早可执行时间与任务的剩余个数
        // 任务种类数
        int m = map.size();
        List<Integer> nextValid = new ArrayList<>();
        List<Integer> ret = new ArrayList<>();
        Set<Map.Entry<Character, Integer>> entries = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entries) {
            nextValid.add(1);
            ret.add(entry.getValue());
        }
        // 时间模拟
        int time = 0;
        for (int i = 0; i < tasks.length; i++) {
            ++time;
            // 这一步是为了优化算法,为了避免n过大,但是time还逐个搜索的麻烦
            int minNextValid = Integer.MAX_VALUE;
            for (int j = 0; j < m; j++) {
                if(ret.get(j) != 0){
                    minNextValid = Math.min(minNextValid, nextValid.get(j));
                }
            }
            time = Math.max(minNextValid, time);
            int best = -1;
            for (int j = 0; j < m; j++) {
                if(ret.get(j) != 0 && nextValid.get(j) <= time){
                    // 每次选取剩余数量最佳的任务
                    if(best == -1 || ret.get(j) > ret.get(best)){
                        best = j;
                    }
                }
            }
            nextValid.set(best, time + n + 1);
            ret.set(best, ret.get(best) - 1);
        }
        return time;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值