Video Stitching

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;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值