最小处理时间
难度:
标签:
题目描述
You have a certain number of processors, each having 4 cores. The number of tasks to be executed is four times the number of processors. Each task must be assigned to a unique core, and each core can only be used once.
You are given an array processorTime
representing the time each processor becomes available and an array tasks
representing how long each task takes to complete. Return the minimum time needed to complete all tasks.
Example 1:
Input: processorTime = [8,10], tasks = [2,2,3,1,8,7,4,5]
Output: 16
Explanation:
Assign the tasks at indices 4, 5, 6, 7 to the first processor which becomes available at time = 8
, and the tasks at indices 0, 1, 2, 3 to the second processor which becomes available at time = 10
.
The time taken by the first processor to finish the execution of all tasks is max(8 + 8, 8 + 7, 8 + 4, 8 + 5) = 16
.
The time taken by the second processor to finish the execution of all tasks is max(10 + 2, 10 + 2, 10 + 3, 10 + 1) = 13
.
Example 2:
Input: processorTime = [10,20], tasks = [2,3,1,2,5,8,4,3]
Output: 23
Explanation:
Assign the tasks at indices 1, 4, 5, 6 to the first processor and the others to the second processor.
The time taken by the first processor to finish the execution of all tasks is max(10 + 3, 10 + 5, 10 + 8, 10 + 4) = 18
.
The time taken by the second processor to finish the execution of all tasks is max(20 + 2, 20 + 1, 20 + 2, 20 + 3) = 23
.
Constraints:
1 <= n == processorTime.length <= 25000
1 <= tasks.length <= 105
0 <= processorTime[i] <= 109
1 <= tasks[i] <= 109
tasks.length == 4 * n
代码结果
运行时间: 92 ms, 内存: 31.0 MB
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.stream.IntStream;
// 思路:
// 1. 将任务数组按任务时间从大到小排序。
// 2. 为每个处理器建立一个最小堆,用于记录其每个核心的空闲时间。
// 3. 逐个将任务分配给最早空闲的核心。
// 4. 返回所有处理器中完成所有任务的最晚时间。
public class Solution {
public int minTime(int[] processorTime, int[] tasks) {
// 将任务数组按任务时间从大到小排序
Arrays.sort(tasks);
int n = processorTime.length;
int cores = 4; // 每个处理器4个核心
// 最小堆,用于记录每个核心的空闲时间
PriorityQueue<Integer>[] processors = IntStream.range(0, n)
.mapToObj(i -> new PriorityQueue<Integer>())
.toArray(PriorityQueue[]::new);
IntStream.range(0, n).forEach(i -> IntStream.range(0, cores)
.forEach(j -> processors[i].offer(processorTime[i])));
// 任务从大到小分配
IntStream.iterate(tasks.length - 1, i -> i >= 0, i -> i - 1).forEach(i -> {
// 寻找最早空闲的核心
int minIndex = IntStream.range(0, n)
.reduce((a, b) -> processors[a].peek() < processors[b].peek() ? a : b)
.getAsInt();
// 取出最早空闲的核心时间并更新
int earliest = processors[minIndex].poll();
processors[minIndex].offer(earliest + tasks[i]);
});
// 找到所有处理器中最晚的完成时间
return IntStream.range(0, n)
.flatMap(i -> processors[i].stream().mapToInt(Integer::intValue))
.max()
.orElse(0);
}
}
解释
方法:
时间复杂度:
空间复杂度: