Accepted Python code, could it be simpler?


  • 0
    H
    class Solution:
    	def insert(self, intervals, newInterval):
    		if intervals == []:
    			return [newInterval]
    		#add Intervals to both end of intervals 
    		left = Interval(-10000000, -10000000)
    		right = Interval(10000000, 10000000)
    		intervals.insert(0, left)
    		intervals.append(right)
    
            #find the position of newInterval.start and newInterval.end
    		s = self.where(intervals, newInterval.start)
    		e = self.where(intervals, newInterval.end)
    
    		if s[0] == 0 and e[0] == 0: # if both start and end are outside any Interval, delete the Intervals between them
    			for i in range(0, e[1] - s[1]):
    				del intervals[(s[1] + 1)]
    			intervals.insert(s[1] + 1, newInterval)
    			return intervals[1:-1] # cut the begin and end
    
    		if s[0] == e[0] and s[1] != e[1]: # both inside Interval
    			new1 = Interval(intervals[s[1]].start, intervals[e[1]].end) # make a new Interval
    			for i in range(s[1], e[1] + 1): # delete the Intervals in between
    				del intervals[s[1]]
    			intervals.insert(s[1], new1) # insert the new one
    
    		if s[0] == 0 and e[0] == 1: # the start is outside and the end is inside
    			new1 = Interval(newInterval.start, intervals[e[1]].end)
    			for i in range(s[1], e[1]):
    				del intervals[s[1] + 1]
    			intervals.insert(s[1] + 1, new1)
    
    		if s[0] == 1 and e[0] == 0:
    			new2 = Interval(intervals[s[1]].start, newInterval.end)
    			for i in range(s[1], e[1] + 1):
    				del intervals[s[1]]
    			intervals.insert(s[1], new2)
    		return intervals[1:-1]
    
    	def where(self, intervals, s):
    		flag = [] 
    		for i in range(len(intervals)):
    			if s >= intervals[i].start and s <= intervals[i].end:
    				flag = [1, i] # inside ith Interval of intervals
    				return flag
    		for i in range(len(intervals)):
    			if s >= intervals[i].end and s <= intervals[i + 1].start:
    				flag = [0, i] # right behind ith Interval and outside
    				return flag

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.