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