LeetCode每日一题(2589. Minimum Time to Complete All Tasks)

There is a computer that can run an unlimited number of tasks at the same time. You are given a 2D integer array tasks where tasks[i] = [starti, endi, durationi] indicates that the ith task should run for a total of durationi seconds (not necessarily continuous) within the inclusive time range [starti, endi].

You may turn on the computer only when it needs to run a task. You can also turn it off if it is idle.

Return the minimum time during which the computer should be turned on to complete all tasks.

Example 1:

Input: tasks = [[2,3,1],[4,5,1],[1,5,2]]
Output: 2

Explanation:

  • The first task can be run in the inclusive time range [2, 2].
  • The second task can be run in the inclusive time range [5, 5].
  • The third task can be run in the two inclusive time ranges [2, 2] and [5, 5].
    The computer will be on for a total of 2 seconds.

Example 2:

Input: tasks = [[1,3,2],[2,5,3],[5,6,2]]
Output: 4

Explanation:

  • The first task can be run in the inclusive time range [2, 3].
  • The second task can be run in the inclusive time ranges [2, 3] and [5, 5].
  • The third task can be run in the two inclusive time range [5, 6].
    The computer will be on for a total of 4 seconds.

Constraints:

  • 1 <= tasks.length <= 2000
  • tasks[i].length == 3
  • 1 <= starti, endi <= 2000
  • 1 <= durationi <= endi - starti + 1

高端的问题往往只需要最朴素的解法

  1. 按 end 升序排序
  2. 遍历 tasks, 要想让完成当前 task 所花费的时间价值最大化, 我们要尽可能晚的完成 task, 原因么, 因为是 end 升序, 所以 tasks[i][1] <= tasks[i+1][1], 但是 tasks[i+1][0]不一定会小于 tasks[i][0], 所以要想尽可能让完成 task[i]的时间区间同时也在 tasks[i+1]的区间内, 我们要尽可能的将完成 tasks[i]的时间区间向后移动

关于如何计算 tasks[i]还需要花费多长时间, 我是用了最直观的方法, 1 <= start, end <= 2000, 所以我们就把所有时间片都列出来, times = [false; 2001], 这样我们就可以记录哪些时间片已经占用了, 而这些时间片如果处于 tasks[i][0]与 tasks[i][1]之间, 那证明 tasks[i]已经处理过一部分了, 需要用 tasks[i][2]减去这些时间片, 剩下的才是需要花费的时间, 注意, 最后剩余的时间可能<=0, 这意味着 task[i]已经完成, 不需要再花时间去做, 相反, 如果剩余的 tasks[i][2]>0, 我们则需要利用那些距离 tasks[i][1]最近的且没有被占用的时间片来完成 task[i]



impl Solution {
    pub fn find_minimum_time(mut tasks: Vec<Vec<i32>>) -> i32 {
        tasks.sort_by_key(|t| (t[1]));
        let mut times = vec![false; 2001];
        let mut ans = 0;
        for i in 0..tasks.len() {
            let (start, end, mut dur) = (tasks[i][0], tasks[i][1], tasks[i][2]);
            for j in start as usize..=end as usize {
                if times[j] {
                    dur -= 1;
                }
            }
            let mut j = end as usize;
            while dur > 0 {
                if !times[j] {
                    times[j] = true;
                    ans += 1;
                    dur -= 1;
                }
                j -= 1;
            }
        }
        ans
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)