You are given a series of video clips from a sporting event that lasted time
seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array clips
where clips[i] = [starti, endi]
indicates that the ith clip started at starti
and ended at endi
.
We can cut these clips into segments freely.
- For example, a clip
[0, 7]
can be cut into segments[0, 1] + [1, 3] + [3, 7]
.
Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]
. If the task is impossible, return -1
.
Example 1:
Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10 Output: 3 Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips. Then, we can reconstruct the sporting event as follows: We cut [1,9] into segments [1,2] + [2,8] + [8,9]. Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].
思路:这题跟Minimum Number of Taps to Open to Water a Garden一模一样。
sort by start 解决问题:=> the minimum number of intervals to cover the whole range.
sort by end 解决问题: => the maximum number of non-overlapping intervals.
算法就是:sort by start, 因为前面的也要cover,首先找一个end最大的,然后在start <= end的所有interval中找end最大的。这样就是greedy的思想;如果nextfar >= T, 那么停止,已经找完了,如果nextfar == far说明走不动了,return-1;
class Solution {
public int videoStitching(int[][] clips, int time) {
Arrays.sort(clips, (a, b) -> (a[0] != b[0] ? a[0] - b[0] : b[1] - a[1]));
if(clips[0][0] != 0) {
return -1;
}
int i = 0;
int far = 0;
int count = 0;
while(i < clips.length) {
int nextfar = far;
while(i < clips.length && clips[i][0] <= far) {
nextfar = Math.max(nextfar, clips[i][1]);
i++;
}
count++;
if(nextfar >= time) {
return count;
} else if(nextfar == far) {
return -1;
}
far = nextfar;
}
return -1;
}
}