leetcode
leetcode 951 ~ 1000
视频拼接

视频拼接

难度:

标签:

题目描述

代码结果

运行时间: 25 ms, 内存: 16.1 MB


// Java Stream API solution for the problem
// The solution follows the same logic as above but utilizes Java Stream for sorting the clips.
// The rest of the logic remains the same: we sort the clips, iterate through them, and keep track of the farthest we can go with the current set of clips.

import java.util.Arrays;
import java.util.Comparator;

public class VideoStitchingStream {
    public int videoStitching(int[][] clips, int time) {
        // Sort clips using Stream
        int[][] sortedClips = Arrays.stream(clips)
            .sorted(Comparator.comparingInt((int[] a) -> a[0]).thenComparingInt(a -> -a[1]))
            .toArray(int[][]::new);
        int end = 0, farthest = 0, count = 0;
        int i = 0;
        while (i < sortedClips.length && end < time) {
            while (i < sortedClips.length && sortedClips[i][0] <= end) {
                farthest = Math.max(farthest, sortedClips[i][1]);
                i++;
            }
            if (end == farthest) return -1; // Can't move forward
            end = farthest;
            count++;
        }
        return end >= time ? count : -1;
    }
}

解释

方法:

该题解采用的是贪心算法。首先,创建一个数组maxn,长度为time,用于记录每个时间点可以达到的最远结束时间。遍历输入的视频片段,如果片段的开始时间小于time,更新maxn数组中对应开始时间的位置为当前片段的结束时间和原有值的较大者。接着,遍历从0到time的时间点,使用变量last记录当前能到达的最远时间,pre记录前一个被选择的片段的结束时间,ret记录需要的片段数量。如果当前时间点i等于last,说明无法继续向前,返回-1表示不能覆盖整个时间段。如果i等于pre,说明需要选择一个新的片段,增加ret并更新pre为last。最后返回ret作为结果。

时间复杂度:

O(n + time)

空间复杂度:

O(time)

代码细节讲解

🦆
在算法中,如果`maxn`数组中某个位置的值未被更新(即仍为0),这会如何影响算法的输出和片段选择?
在算法中,如果`maxn`数组的某个位置值未被更新,即该位置的值仍为0,这意味着从该时间点开始没有任何视频片段。这将直接影响算法的执行流程和输出结果。具体地,当遍历到这个时间点时,由于没有可用的片段延伸覆盖范围,变量`last`(表示当前能到达的最远时间)不会增加,从而可能导致在这一时间点时`i`等于`last`。根据算法逻辑,这种情况下算法将返回-1,表示无法覆盖整个0到time的时间段,因此无法完成视频拼接任务。
🦆
算法如何处理视频片段完全不覆盖`[0, time]`区间的情况?是否有什么特殊的返回值或处理方式?
算法通过检查是否存在片段从时间0开始的情况来处理视频片段完全不覆盖`[0, time]`区间的情况。特别地,如果在遍历过程中在时间0的位置`maxn[0]`值为0,这意味着没有任何视频片段开始于时间0。在这种情况下,变量`last`将一直保持为0,导致在第一次迭代时`i`将等于`last`。根据算法的设计,这将直接触发返回-1的条件,表明算法无法从0开始覆盖任何部分的时间段。因此,-1作为特殊的返回值,用于表示视频片段无法覆盖整个所需的时间段。

相关问题