2023-3-13 刷题情况
完成所有任务的最少时间
题目描述
你有一台电脑,它可以 同时 运行无数个任务。给你一个二维整数数组 tasks ,其中 tasks[i] = [starti, endi, durationi] 表示第 i 个任务需要在 闭区间 时间段 [starti, endi] 内运行 durationi 个整数时间点(但不需要连续)。
当电脑需要运行任务时,你可以打开电脑,如果空闲时,你可以将电脑关闭。
请你返回完成所有任务的情况下,电脑最少需要运行多少秒。
样例
样例输入
tasks = [[2,3,1],[4,5,1],[1,5,2]]
tasks = [[1,3,2],[2,5,3],[5,6,2]]
样例输出
2
4
提示
- 1<=tasks.length<=20001 <= tasks.length <= 20001<=tasks.length<=2000
- tasks[i].length==3tasks[i].length == 3tasks[i].length==3
- 1<=starti,endi<=20001 <= starti, endi <= 20001<=starti,endi<=2000
- 1<=durationi<=endi−starti+11 <= durationi <= endi - starti + 11<=durationi<=endi−starti+1
思路
贪心思想,按照右区间边界排序,对于所有能确定的区间都尽量靠右。
代码实现
class Solution {public int findMinimumTime(int[][] tasks) {Arrays.sort(tasks, (a, b) -> a[1] - b[1]);int ans = 0;boolean[] vis = new boolean[20001];for(var task : tasks){int start = task[0], end = task[1], d = task[2];for(int i = start; i <= end; ++i) if(vis[i]) --d;for(int i = end; d > 0; --i){if(!vis[i]){vis[i] = true;--d;++ans;}}}return ans;}
}