Skip to content

Commit 21c7ded

Browse files
committed
merge intervals
1 parent 26c302c commit 21c7ded

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of
3+
disjoint intervals.
4+
5+
For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be:
6+
7+
[1, 1]
8+
[1, 1], [3, 3]
9+
[1, 1], [3, 3], [7, 7]
10+
[1, 3], [7, 7]
11+
[1, 3], [6, 7]
12+
Follow up:
13+
What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size?
14+
"""
15+
__author__ = 'Daniel'
16+
17+
18+
# Definition for an interval.
19+
class Interval(object):
20+
def __init__(self, s=0, e=0):
21+
self.start = s
22+
self.end = e
23+
24+
25+
class SummaryRanges(object):
26+
def __init__(self):
27+
"""
28+
BST is the most efficient, while heap is simple to write
29+
Initialize your data structure here.
30+
"""
31+
self.itvls = []
32+
33+
def addNum(self, val):
34+
"""
35+
O(lg n)
36+
:type val: int
37+
:rtype: void
38+
"""
39+
self.itvls.append(Interval(val, val))
40+
41+
def getIntervals(self):
42+
"""
43+
O(n lg n)
44+
:rtype: List[Interval]
45+
"""
46+
self.itvls.sort(key=lambda x: x.start)
47+
48+
ret = [self.itvls[0]]
49+
for itvl in self.itvls[1:]:
50+
pre = ret[-1]
51+
if itvl.start <= pre.end + 1:
52+
pre.end = max(itvl.end, pre.end)
53+
else:
54+
ret.append(itvl)
55+
56+
self.itvls = ret
57+
return ret
58+
59+
# Your SummaryRanges object will be instantiated and called as such:
60+
# obj = SummaryRanges()
61+
# obj.addNum(val)
62+
# param_2 = obj.getIntervals()

0 commit comments

Comments
 (0)