zoukankan      html  css  js  c++  java
  • Round Robin轮询算法

    名字高大上,其实就是循环、遍历这个意思,
    不过它强调的一个轮转,且每个均匀,所以通常有取模的操作。
    比如在调度中应用:
    Round Robin 是一种CPU 调度算法,其中每个进程以循环方式分配一个固定的时隙。

    • 它简单、易于实现且无饥饿,因为所有进程都获得公平的 CPU 份额。
    • 作为核心的 CPU 调度中最常用的技术之一。
    • 它是抢占式的,因为进程最多只能在固定的时间片内分配 CPU。
    • 它的缺点是更多的上下文切换开销。

    比如在Go和Redis中:
    将任务通过取模的方式,分给每个线程的本地队列

    LC 68. 文本左右对齐

    困难题,模拟,主要就是字符串填充。其中的round_robin函数就是轮流给前n-1的单词添加一个空格,直到空格填完。

    class Solution:
        def round_robin(self, words, space_num): # 轮流填充
            n = len(words)
            for i in range(space_num):
                words[i%((n-1) or 1)] += ' '
            
        def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
            res, cur, cur_len = [], [], 0 
            for word in words:
                if(cur_len + len(cur) + len(word) > maxWidth):
                    self.round_robin(cur, maxWidth-cur_len)
                    line = ''.join(cur)
                    res.append(line)
                    cur, cur_len = [], 0
                cur.append(word)
                cur_len += len(word)
            # 最后一行
            res.append(' '.join(cur).ljust(maxWidth))
            return res
    

    LC 621. 任务调度器

    题意:带冷却时间的轮流执行
    方法:由频率最高的决定,其实是道数学题,不需要去逐一填充。前m-1段默认补充至n+1,最后一段不需要补充,而最后一段的长度就看有几个最高频率的。

    class Solution {
    public:
        // 
        int cnt[26];
        int leastInterval(vector<char>& tasks, int n) {
            int len = tasks.size();
            for(int i = 0;i < len;i++)  cnt[tasks[i]-'A']++;
            sort(cnt, cnt+26);
            int res = (cnt[25]-1)*(n+1);  // 前m-1段排满
            for(int i = 25;i >= 0;i--)
            {
                if(cnt[i] != cnt[25]) break; 
                res++;   // 加上最后一段
            }
            res = max(res, len);
            return res;
        }
    };
    

    参考链接

    1. leetcode 68:Text Justification(Round Robin算法应用
    2. https://leetcode-cn.com/problems/task-scheduler/comments/30672
    个性签名:时间会解决一切
  • 相关阅读:
    I
    H
    G
    F
    E
    论js里面的for循环
    js常见问题之为什么点击弹出的i总是最后一个
    array类型的方法
    string类型的方法
    for in在对象和数组中的应用
  • 原文地址:https://www.cnblogs.com/lfri/p/15775919.html
Copyright © 2011-2022 走看看