56. Merge Intervals Leetcode

本文介绍了一种直接计算方法来解决合并重叠区间的问题。首先对区间按照起始位置排序,然后通过比较当前区间与前一个区间的起止点来决定是否合并。时间复杂度为O(nlogn),体现了排序步骤的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a collection of intervals, merge all overlapping intervals.


For example,
Given [1,3],[2,6],[8,10],[15,18],

return [1,6],[8,10],[15,18].


这道题目做法有很多中,有用stack的也有直接计算的。这里我采用直接计算的方法。

1.将intervals按照start进行排序

2.然后比较start 如果有 pre.start<=post.start<=pre.end 那pre.end=max(pre.end,post.end) 否者的话就不用进行merge



因为要进行排序,所以时间复杂度为O(nlogn+n)= O(nlogn)

We need to sort the intervals based on start, then we compare pre.start with post.start and pre.end. If post.start fall in [pre.start, pre.end] we need to merge the two based on 

max(pre.end,post.end)

otherwise, we add the interval to the solution directly.

The time complexity in this problem is O(nlogn)

# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    # @param intervals, a list of Interval
    # @return a list of Interval
    def merge(self, intervals):
        solution=[]
        intervals.sort(key=lambda x:x.start)
        for index in range(len(intervals)):
            if solution==[]:
                solution.append(intervals[index])
            else:
                size=len(solution)
                if solution[size-1].start<=intervals[index].start<=solution[size-1].end:
                    solution[size-1].end=max(solution[size-1].end,intervals[index].end)
                else:
                    solution.append(intervals[index])
        return solution


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值