leetcode-651.Task Scheduler

Posted janh

tags:

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

621. Task Scheduler(Medium)
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-651.Task Scheduler的主要内容,如果未能解决你的问题,请参考以下文章

text cron schedul表达

记一次Laravel 定时任务schedul:run未执行的处理

K8S单master部署三:APIserver+Controller-Manager+Schedul

Spring中使用Quartz

openstack下

scrapy爬虫框架