1. 程式人生 > >[leetcode]621. Task Scheduler

[leetcode]621. Task Scheduler

[leetcode]621. Task Scheduler


Analysis

中午吃啥—— [每天刷題並不難0.0]

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.
在這裡插入圖片描述

Explanation:

敲詳細:

https://leetcode.com/problems/task-scheduler/discuss/104500/Java-O(n)-time-O(1)-space-1-pass-no-sorting-solution-with-detailed-explanation

Implement

class Solution {
public:
    int leastInterval(vector<char>& tasks, int n) {
        vector<int> cnt(26);
        int len = tasks.size();
        int
maxcnt = 1; for(char t:tasks){ cnt[t-'A']++; } sort(cnt.begin(), cnt.end()); for(int i=24; i>=0; i--){ if(cnt[i] == cnt[25]) maxcnt++; else break; } int partCnt = cnt[25]-1; int emptySlots = partCnt*(n-(maxcnt-1)); int ava = len-cnt[25]*maxcnt; int idels = max(0, emptySlots-ava); int res = len+idels; return res; } };