|
| 1 | +# Definition for an interval. |
| 2 | +# class Interval(object): |
| 3 | +# def __init__(self, s=0, e=0): |
| 4 | +# self.start = s |
| 5 | +# self.end = e |
| 6 | +import bisect |
| 7 | +class SummaryRanges(object): |
| 8 | + |
| 9 | + def __init__(self): |
| 10 | + """ |
| 11 | + Initialize your data structure here. |
| 12 | + """ |
| 13 | + self.numbers = [] |
| 14 | + |
| 15 | + def addNum(self, val): |
| 16 | + """ |
| 17 | + :type val: int |
| 18 | + :rtype: void |
| 19 | + """ |
| 20 | + if not self.numbers: |
| 21 | + self.numbers = [val, val] |
| 22 | + idx = bisect.bisect_left(self.numbers, val) |
| 23 | + mleft, mright = False, False |
| 24 | + if idx%2: |
| 25 | + return |
| 26 | + if idx > 0: |
| 27 | + if self.numbers[idx-1] == val-1: |
| 28 | + mleft = True |
| 29 | + |
| 30 | + if idx < len(self.numbers)-1: |
| 31 | + if self.numbers[idx] == val+1: |
| 32 | + mright = True |
| 33 | + elif self.numbers[idx] == val: |
| 34 | + return |
| 35 | + if not mleft and not mright: |
| 36 | + self.numbers.insert(idx, val) |
| 37 | + self.numbers.insert(idx, val) |
| 38 | + elif not mleft and mright: |
| 39 | + self.numbers[idx] = val |
| 40 | + elif mleft and not mright: |
| 41 | + self.numbers[idx-1] = val |
| 42 | + else: |
| 43 | + del self.numbers[idx-1:idx+1] |
| 44 | + |
| 45 | + def getIntervals(self): |
| 46 | + """ |
| 47 | + :rtype: List[Interval] |
| 48 | + """ |
| 49 | + n = self.numbers |
| 50 | + return [[n[i], n[i+1]] for i in range(0, len(n), 2)] |
| 51 | + |
| 52 | + |
| 53 | +# Your SummaryRanges object will be instantiated and called as such: |
| 54 | +# obj = SummaryRanges() |
| 55 | +# obj.addNum(val) |
| 56 | +# param_2 = obj.getIntervals() |
0 commit comments