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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM