这又是一道没有固定套路,只是纯看自己能不能想出来解法的题目。
https://leetcode.com/problems/task-scheduler/discuss/104500/Java-O(n)-time-O(1)-space-1-pass-no-sorting-solution-with-detailed-explanation
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
vector<int> cnts(26, 0);
int maxCnt = 0;
int maxCntNum = 0;
for (char c : tasks) {
cnts[c-'A']++;
if (cnts[c-'A'] == maxCnt)
++maxCntNum;
else if (cnts[c-'A'] > maxCnt) {
maxCnt = cnts[c-'A'];
maxCntNum = 1;
}
}
int partCount = maxCnt-1;
int partLen = n - (maxCntNum - 1);
int emptySlots = partCount * partLen;
int availableTasks = tasks.size() - maxCnt * maxCntNum;
int idles = max(0, emptySlots - availableTasks);
return tasks.size() + idles;
}
};
总的来说就是贪心,把出现频率最高的安排好了,其他的放到它之间就行了。
详细的看链接