欢迎光临散文网 会员登陆 & 注册

LeetCode 2244. Minimum Rounds to Complete All Tasks

2023-04-21 16:23 作者:您是打尖儿还是住店呢  | 我要投稿

You are given a 0-indexed integer array tasks

where tasks[i] represents the difficulty level of a task. 

In each round, you can complete either 2 or 3 tasks of the same difficulty level.

Return the minimum rounds required to complete all the tasks, 

or -1 if it is not possible to complete all the tasks.

 

Example 1:

Input: tasks = [2,2,3,3,2,4,4,4,4,4]

Output: 4

Explanation: 

To complete all the tasks, a possible plan is:

- In the first round, you complete 3 tasks of difficulty level 2.

- In the second round, you complete 2 tasks of difficulty level 3. 

- In the third round, you complete 3 tasks of difficulty level 4. 

- In the fourth round, you complete 2 tasks of difficulty level 4.   

It can be shown that all the tasks cannot be completed in fewer than 4 rounds, 

so the answer is 4.

Example 2:

Input: tasks = [2,3,3]

Output: -1

Explanation: 

There is only 1 task of difficulty level 2, 

but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.

 

Constraints:

  • 1 <= tasks.length <= 105

  • 1 <= tasks[i] <= 109

所有的任务都要完成,那么我们就去计算每个任务出现的次数,如果出现的次数<2,那么就不能完成,这时候就返回-1;

如果都符合要求,那么就去判断如何用最少的round去完成,那么我们优先用3去判断余数,余数为0,直接全部3, 余数为1,那么相当于最后4个任务要用2次round去完成,

同理余数是2的时候,最后2个任务用1次round完成;

下面就是代码了,主要就是用hashmap即可;

Runtime: 40 ms, faster than 36.31% of Java online submissions for Minimum Rounds to Complete All Tasks.

Memory Usage: 56.8 MB, less than 61.18% of Java online submissions for Minimum Rounds to Complete All Tasks.


LeetCode 2244. Minimum Rounds to Complete All Tasks的评论 (共 条)

分享到微博请遵守国家法律