首页 > 移动平台 > 详细

Merge Overlapping Intervals

时间:2021-07-19 14:49:50      阅读:9      评论:0      收藏:0      [点我收藏+]

refer to: https://www.algoexpert.io/questions/Merge%20Overlapping%20Intervals


Problem Statement

技术分享图片

Sample example

技术分享图片

Analysis

step 1: sort the intervals by their start value

step 2: check if the end value of the previous interval is larger than the start value of the latter interval

技术分享图片

Code

def mergeOverlappingIntervals(intervals):
    # sort the intervals by startinf value.  O(nlogn)
    sortedIntervals = sorted(intervals, key = lambda x: x[0])
    
    mergedIntervals = []# space: O(n)
    currentInterval = sortedIntervals[0]#initialize the currentInterval as the first interval of the intervals
    mergedIntervals.append(currentInterval)#initialize the mergedIntervals as the first interval of the intervals
    
    for nextInterval in sortedIntervals:# for the first iteration, no update
        _, currentIntervalEnd = currentInterval
        nextIntervalStart, nextIntervalEnd = nextInterval
        
        if currentIntervalEnd >= nextIntervalStart: # overlap found, update the end value of interval
            currentInterval[1] = max(currentIntervalEnd, nextIntervalEnd)
        else: # no overlap, add the current(nextInterval) into the mergedIntervals array
            currentInterval = nextInterval
            mergedIntervals.append(currentInterval)
    return mergedIntervals

Time and Space complexity

O(nlogn) time complexity for sorting

O(n) space complexity for store the mergedIntervals(upper bound, all intervals kept)

 

 

 

Merge Overlapping Intervals

原文:https://www.cnblogs.com/LilyLiya/p/15028663.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!