Data Stream as Disjoint Intervals

Problem: Data Stream as Disjoint Intervals

We keep order of input data streams with binary search and insertion.

Code in Python:

# Definition for an interval.
# class Interval(object):
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class SummaryRanges(object):

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

    def addNum(self, val):
        """
        :type val: int
        :rtype: void
        """
        l, r = 0, len(self.numbers)
        while l < r:
            c = (l+r)/2
            if self.numbers[c] > val: r = c
            elif self.numbers[c] < val: l = (l+r+1)/2
            else:
                return
        self.numbers.insert(l, val)

    def getIntervals(self):
        """
        :rtype: List[Interval]
        """
        res = []
        for number in self.numbers:
            if len(res) != 0 and number == res[-1][1] + 1: res[-1][1] = number
            else: res.append([number, number])
        return res


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

results matching ""

    No results matching ""