[621] 任务调度器(20)

91 阅读1分钟

这个题也是思路考船长讲解,代码看助教怎么写,代码倒是不难理解,难得是不常用的_countBy(这个用法写在下面注释中了),对象方法,Object.values()还有一个Object.keys()

这个链接对Object.keys()做详细解释 zhuanlan.zhihu.com/p/40601459

这个链接总结Object.values() Object.keys() 的用法blog.csdn.net/weixin_4367…

/*
 * @lc app=leetcode.cn id=621 lang=javascript
 *
 * [621] 任务调度器
 */

// @lc code=start
/**
 * @param {character[]} tasks
 * @param {number} n
 * @return {number}
 */
var leastInterval = function (tasks, n) {
	// _countBy([], ...属性) 例如 
	/*  _.countBy([6.1, 4.2, 6.3], Math.floor);
	=> { '4': 1, '6': 2 }
  
 _.countBy(['one', 'two', 'three'], 'length');
 => { '3': 2, '5': 1 } */
	// 得到一个tasks中 每个元素出现多少次的对象
	const obj = _.countBy(tasks);
	// 把对象的values值返回到一个数组中
	const arr = Object.values(obj);

	const max = Math.max(...arr);
	let maxCount = 0;

	// 求数组 最大值的次数
	arr.forEach(v => {
		if (v === max) {
			maxCount++;
		}
	})

	// 最后这个还是用船长的思想 对比需要的时间和总任务数量 返回最大的
	
	return Math.max((max - 1) * (n + 1) + maxCount, tasks.length);

};
// @lc code=end