多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
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. ~~~ **Note:** 1. The number of tasks is in the range [1, 10000]. 2. The integer n is in the range [0, 100]. ![](https://img.kancloud.cn/26/17/26170998f48aef1f927a09620cc07024_1087x486.png) ``` /** * @param {character[]} tasks * @param {number} n * @return {number} */ var leastInterval = function(tasks, n) { let q = ''; //队列的执行结果 let Q = {}; //对归类进行存储 tasks.forEach(item =>{ if(Q[item]){ Q[item]++; }else{ Q[item] = 1; } }) while(1){ let keys = Object.keys(Q); if(!keys[0]){ break; } let tmp = []; for(let i=0;i<=n;i++){ let max = 0; let key; let pos; keys.forEach((item,idx) =>{ if(Q[item] > max){ max = Q[item]; key = item; pos = idx; } }) if(key){ tmp.push(key); keys.splice(pos,1); Q[key]--; if(Q[key]<1){ delete Q[key]; } }else{ break; } } q += tmp.join('').padEnd(n+1,'-') } //最后不要出现冷却时间 q = q.replace(/-+$/g,'') return q.length; } ```