[Leetcode] (python): 057-insert Interval

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/insert-interval/

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

Assume that the intervals were initially sorted according to their start times.

Example 1:
Given intervals [1,3],[6,9] , insert and merge in as [2,5] [1,5],[6,9] .

Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16] , insert and merge in as [4,9] [1,2],[3,10],[12,16] .

This is because, the new interval [4,9] overlaps with [3,5],[6,7],[8,10] .

Test instructions Analysis

INPUT:A list of intervals and a new interval

Output:insert the new interval into the list and merge if necessary

Conditions: Insert a new interval into it and merge if necessary

Topic ideas

It feels like the merge interval, so go straight to the Append list, then sort by the previous merge method, and then over ...

AC Code (PYTHON)

1 #Definition for an interval.2 #class Interval (object):3 #def __init__ (self, s=0, e=0):4 #Self.start = s5 #self.end = e6 7 classsolution (object):8     definsert (self, intervals, newinterval):9         """Ten : Type Intervals:list[interval] One : Type Newinterval:interval A : Rtype:list[interval] -         """ - intervals.append (newinterval) theIntervals.sort (key =LambdaX:x.start) -          -Length =len (intervals) -res = [] +          -         ifLength = =0: + res.append (newinterval) A             returnRes at          - res.append (intervals[0]) -          forIinchRange (1, length): -Size =Len (res) -             ifRes[size-1].start <= Intervals[i].start <= res[size-1].end: -Res[size-1].end = Max (Intervals[i].end, res[size-1].end) in             Else: - res.append (intervals[i]) to          +         returnRes -         

[Leetcode] (python): 057-insert 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.