热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

MergeOverlappingIntervals

referto: https:www.algoexpert.ioquestionsMerge%20Overlapping%20IntervalsProblemStatementSa

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)

 


 

 



推荐阅读
author-avatar
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有