LeetCode Task Scheduler

LeetCode Task Scheduler

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 1:

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].

CPU需要处理一系列任务,限制条件是两个相同的任务被处理的时间至少需要间隔n时刻,问CPU最少需要多长时间能处理完所有任务。

比赛没做出来,参考讨论区

根据题意,两个任务被处理至少需要间隔n时刻,所以我们可以认为CPU处理一批任务的循环周期是n+1,比如0时刻处理了任务'A',则至少要到n+1时刻才能再次处理任务'A',中间间隔了n时刻。

假设数量最多的任务的数量是k,则我们至少需要k个周期才能把这个任务处理完。为了让CPU处理的空闲时间更少,我们在一个周期内尽量让CPU处理的任务更丰富。所以想象一下,我们有k个桶,相当于k个周期,每个周期,我们把频率最高的任务拿出来,分发到这最多k个桶中。如果所有不同任务都分发完了还没有填满一个桶,则说明该桶内(周期内)CPU需要空闲等待。

比如样例中,最高频的任务是A和B,都是3,所以我们至少需要3个桶。每个桶的容量是n+1=3,相当于相同任务的距离是3。每次我们把A和B扔到不同的桶中,前两个桶各有一个空闲等待,第三个桶因为结束了,所以不需等待。

因为每次都需要取出最高频的任务去分发,所以用一个优先队列来实时更新频率排名。

完整代码如下:

class Solution {
public:
	int leastInterval(vector<char>& tasks, int n) {
		map<char, int> count;
		for (const auto& c : tasks)++count;
		priority_queue<pair<int, char>> pq;
		for (const auto& p : count)pq.push({ p.second,p.first });
		int cycle = n + 1, time = 0;
		while (!pq.empty()) {
			vector<pair<int, char>> tmp;
			int tsk = 0;
			for (int i = 0; i < cycle; ++i) {
				if (!pq.empty()) {
					tmp.push_back(pq.top());
					pq.pop();
					++tsk;
				}
			}
			for (auto& t : tmp) {
				if (--t.first) {
					pq.push(t);
				}
			}
			time += pq.empty() ? tsk : cycle;
		}
		return time;
	}
};

本代码提交AC,用时95MS。

Leave a Reply

Your email address will not be published. Required fields are marked *