Merging Overlapping Intervals

前端 未结 4 2041
花落未央
花落未央 2020-12-10 14:31

Currently, I have intervals of:

temp_tuple = [[-25, -14], [-21, -16], [-20, -15], [-10, -7], [-8, -5], [-6, -3], [2, 4], [2, 3], [3, 6], [12, 15], [13, 18],          


        
4条回答
  •  忘掉有多难
    2020-12-10 14:52

    #Given an array of intervals in sorted order and a new interval, return a sorted array after merging the interval
    
    def mergeinter(intervals,newinter):
        n = len(intervals)
        start = newinter[0]# we mark the start and end of the new interval to be merged
        end = newinter[1]
        right,left = 0,0
        while right < n:# we track where this new interval belongs, i.e. how many interval are to the left of it and how many are to the right
            if start <= intervals[right][1]:# we find the first interval before which it fits
                if end < intervals[right][0]:# this checks if the interval is disjoint and lies between two given intervals
                    break# in this case we have nothing to do and go to line 29 directly
                start = min(start,intervals[right][0])# if it intersects with the given intervals then we just update and merge the ends
                end = max(end,intervals[right][1])
            else:# counting how many to the left continuing from line 20
                left += 1 
            right += 1# moving right to find the fit continuation of line 20 and even if we merge in line 25, we go to the next interval before
        return intervals[:left] + [(start,end)] + intervals[right:] # we return starting from the next interval
    
    #Given a collection of intervals, merge all overlapping intervals and return sorted list of disjoint intervals.
    
    def merge(I):
        I.sort(key:lambda i:i[0])# sorting according to the start of all intervals
        res = []# we start from the last of the given arr of lists and check the ends of the intervals and merge from the end
        for i in I:
            if not res or res[-1][0] < i[1]:# if res is empty then we put an elem in it from I
                res.append(i)# if there is no overlap, just add it
            else:
                res[-1][1] = max(i[1], res[-1][1])# here we merge from the end so that res remains sorted
        return res
    

提交回复
热议问题