Fork me on GitHub

Data Stream as Disjoint Intervals

Description

https://leetcode.com/problems/data-stream-as-disjoint-intervals/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e

class SummaryRanges:

def __init__(self):
"""
Initialize your data structure here.
"""
self.interval_list = []

def addNum(self, val):
"""
:type val: int
:rtype: void
"""
index = 0
while index < len(self.interval_list):
if val <= self.interval_list[index].start:
break
index += 1
independ = True
if index >= 1 and (self.interval_list[index - 1].end + 1 == val or self.interval_list[index - 1].end == val):
self.interval_list[index - 1].end = val
independ = False
if index < len(self.interval_list) and (self.interval_list[index].start == val + 1 or self.interval_list[index].start ==val):
self.interval_list[index].start = val
independ = False
if index >= 1 and index < len(self.interval_list) and self.interval_list[index].start == self.interval_list[index - 1].end:
self.interval_list[index - 1].end = self.interval_list[index].end
del self.interval_list[index]
index -= 1

if independ == True and (index == 0 or val > self.interval_list[index - 1].end + 1):
self.interval_list.insert(index, Interval(val, val))

def getIntervals(self):
"""
:rtype: List[Interval]
"""
return self.interval_list


# Your SummaryRanges object will be instantiated and called as such:
# obj = SummaryRanges()
# obj.addNum(val)
# param_2 = obj.getIntervals()