[Leetcode one question per day] 1024. Video stitching (interval preprocessing, greedy)

Leetcode's daily question
link: 1024. Video splicing
problem solving idea: preprocess the given interval to obtain the largest end point corresponding to each left end point. It traverses the entire interval, and covers the maximum length that can be reached for each dynamic update. If a certain interval is completely covered, the number of intervals +1.
answer:

class Solution:
    def videoStitching(self, clips: List[List[int]], T: int) -> int:
        
        # 以左端点开头的最大右端点
        max_index = [0 for i in range(T + 1)]

        for example in clips:
            # print(example)
            if example[0] <= T:
                max_index[example[0]] = max(max_index[example[0]], example[1])
        
        # cnt记录片段数量, pre记录前一个找到的右端点位置,last表示当前的最大右端点
        cnt, pre, last = 0, 0, 0
        for t in range(T):
            last = max(max_index[t], last)

            # 有空缺, 不能完全覆盖。 由于t < T所以不用担心最后一个元素
            if t == last:
                return -1

            # 匹配到前一个的结尾,覆盖了整个区间,可以找新的区间了    
            if t == pre:
                cnt += 1
                pre = last
        
        return cnt
        
            

Guess you like

Origin blog.csdn.net/qq_37753409/article/details/109258321