LeetCode Merge Intervals

Source: Internet
Author: User

LeetCode Merge Intervals
Original question

Multiple data segments are provided, and the data segments connected at the beginning and end are merged.

Note:

The given data segment is out of order

Example:

Input: intervals = [1, 3], [2, 6], [8, 10], [15, 18]

Output: [], [], []

Solutions

First, sort all data segments by start, so that the data segments that may be connected can be placed in adjacent locations. Traverse the data segment and compare it with the last data segment in the result set. If the data segment can be merged, It is merged. Otherwise, it is added to the result set.

AC Source Code
# Definition for an interval.class Interval(object):    def __init__(self, s=0, e=0):        self.start = s        self.end = e    # To print the result    def __str__(self):        return "[" + str(self.start) + "," + str(self.end) + "]"class Solution(object):    def merge(self, intervals):        """        :type intervals: List[Interval]        :rtype: List[Interval]        """        result = []        if not intervals:            return result        intervals.sort(key=lambda x: x.start)        result.append(intervals[0])        for interval in intervals[1:]:            prev = result[-1]            if prev.end >= interval.start:                prev.end = max(prev.end, interval.end)            else:                result.append(interval)        return resultif __name__ == "__main__":    intervals = Solution().merge([Interval(1, 3), Interval(2, 6), Interval(8, 10), Interval(15, 18)])    for interval in intervals:        print(interval)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.