leetcode-621-CPU 任务调度

Posted janh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-621-CPU 任务调度相关的知识,希望对你有一定的参考价值。

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.


Example:

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

解法一: 计算得到词频最大的字符,该字符相邻最大的数组偏移小于 n
通过 HashMap 统计词频,PriorityQueue 保证有序性

public int leastInterval(char[] tasks, int n) {
    Map<Character, Integer> freqs = new HashMap<>();
    for (int i = 0; i < tasks.length; i++)
        freqs.put(tasks[i], freqs.getOrDefault(tasks[i], 0) + 1);

    PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
            (a,b) -> a.getValue() != b.getValue() ? b.getValue() - a.getValue() : a.getKey() - b.getKey());
    pq.addAll(freqs.entrySet());

    int count = 0;
    int maxFreq = pq.peek().getValue();
    while (!pq.isEmpty() && pq.peek().getValue() == maxFreq) {
        pq.poll();
        count ++;
    }
    return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + count);
}

解法二: 通过 HashMap 统计原始词频, LinkedHash 根据 Map.Entry.getValue() 进行排序

public int leastInterval(char[] tasks, int n) {
    Map<Character, Integer> freqs = new HashMap<>();
    for (int i = 0; i < tasks.length; i++)
        freqs.put(tasks[i], freqs.getOrDefault(tasks[i], 0) + 1);

    freqs = sortByValue(freqs);
    int maxFreq = freqs.entrySet().iterator().next().getValue();
    int count = 0;
    for (Map.Entry<Character, Integer> entry : freqs.entrySet()) {
        if (entry.getValue() == maxFreq)
            count ++;
        else
            break;
    }
    return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + count);
}

private Map<Character, Integer> sortByValue(Map<Character, Integer> map) {
    List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
    list.sort((o1, o2) -> !o1.getValue().equals(o2.getValue()) ? Integer.compare(o2.getValue(), o1.getValue()) : Character.compare(o1.getKey(), o2.getKey()));
    Map<Character, Integer> newMap = new LinkedHashMap<>();
    for (Map.Entry<Character, Integer> entry : list)
        newMap.put(entry.getKey(), entry.getValue());
    return newMap;
}

以上是关于leetcode-621-CPU 任务调度的主要内容,如果未能解决你的问题,请参考以下文章

用于调度代码重复运行的 Windows 任务调度程序有多可靠?

一天一门编程语言用 Go 语言实现一个 DAG 任务调度系统的API 接口代码

ThreadX调度锁,任务锁和中断锁(调度阀值)

译文:18个实用的JavaScript代码片段,助你快速处理日常编程任务

详解基于 Cortex-M3 的任务调度(下)

详解基于 Cortex-M3 的任务调度(下)