LeetCode Insert Interval

Source: Internet
Author: User

LeetCode Insert Interval
Original question

Multiple non-overlapping data segments are provided. Now, insert a data segment and merge the overlapping data segments.

Note:

The given CIDR blocks are sorted by the starting position.

Example:

Input: intervals = [2, 6], [8, 10], [15, 18], newInterval = [13, 16]

Output: [2, 6], [8, 10], [13, 18]

Solutions

The simplest way is to reuse the Merge Intervals method. You only need to add the new data segment to the set first, but the efficiency is not high. Since the original data segments are ordered and not overlapped, we only need to find which data segments overlap with the new data segments, merge these data segments, and add the left and right data segments.

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 insert(self, intervals, newInterval):        start, end = newInterval.start, newInterval.end        left = list(filter(lambda x: x.end < start, intervals))        right = list(filter(lambda x: x.start > end, intervals))        if len(left) + len(right) != len(intervals):            start = min(start, intervals[len(left)].start)            end = max(end, intervals[-len(right) - 1].end)        return left + [Interval(start, end)] + rightif __name__ == "__main__":    intervals = Solution().insert([Interval(2, 6), Interval(8, 10), Interval(15, 18)], Interval(13, 16))    for interval in intervals:        print(interval)

Please check out my Github for relevant source code.

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.