I wrote function, that input array is list of intervals and returns nonoverlapping intervals. Here is the function:
def mergeOverlappingIntervals(intervals):
new=[]
i=0
while i <len(intervals):
if intervals[i][1]<intervals[i 1][0]:
new.append(intervals[i])
i =1
else:
p1=i
p2=i
while intervals[i][1]<=intervals[i 1][0]:
i =1
p2 =1
new.append([intervals[p1][0],intervals[p2][1]])
i=p2
return new
but this function contains infinite loops. It is unclear to me, why this function contains infinite loops and does not get expected outputs. Example of inputs:
interval=[
[1, 2],
[3, 5],
[4, 7],
[6, 8],
[9, 10]
]
outputs=[
[1, 2],
[3, 8],
[9, 10]
]
CodePudding user response:
Your inner while loop uses the wrong condition. You want to merge two intervals when intervals[i][1]
is greater than or equal to, not less than or equal to, intervals[i 1][0]
.
while intervals[i][1] >= intervals[i 1][0]:
i = 1
p2 = 1
There may be other issues, but this one stands out as the primary problem.