视频拼接
难度:
标签:
题目描述
代码结果
运行时间: 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),这会如何影响算法的输出和片段选择?
▷🦆
算法如何处理视频片段完全不覆盖`[0, time]`区间的情况?是否有什么特殊的返回值或处理方式?
▷