-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0352-data-stream-as-disjoint-intervals.py
More file actions
45 lines (35 loc) · 1019 Bytes
/
0352-data-stream-as-disjoint-intervals.py
File metadata and controls
45 lines (35 loc) · 1019 Bytes
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
# time complexity: O(n)
# space complexity: O(1)
from typing import List
class SummaryRanges:
def __init__(self):
self.nums = set()
def addNum(self, value: int) -> None:
self.nums.add(value)
def getIntervals(self) -> List[List[int]]:
intervals = []
seen = set()
for num in self.nums:
if num in seen:
continue
left = num
while left - 1 in self.nums:
left -= 1
seen.add(left)
right = num
while right + 1 in self.nums:
right += 1
seen.add(right)
intervals.append([left, right])
return sorted(intervals)
summaryRanges = SummaryRanges()
summaryRanges.addNum(1)
summaryRanges.getIntervals()
summaryRanges.addNum(3)
summaryRanges.getIntervals()
summaryRanges.addNum(7)
summaryRanges.getIntervals()
summaryRanges.addNum(2)
summaryRanges.getIntervals()
summaryRanges.addNum(6)
summaryRanges.getIntervals()