python, using bisect - O(long(n)) addNum, O(1) findMedian


  • 0
    S
    import bisect
    class MedianFinder(object):
    
        def __init__(self):
            """
            initialize your data structure here.
            """
            self.data = []
            self.n    = 0
            
    
        def addNum(self, num):
            """
            :type num: int
            :rtype: void
            """
            self.n += 1
            self.data.insert( bisect.bisect_left(self.data,num), num )
            
    
        def findMedian(self):
            """
            :rtype: float
            """
            if self.n % 2 != 0 : # odd number of items
                return self.data[self.n//2]
            else: # n even number of items
                return  float ( (self.data[self.n//2] + self.data[ (self.n-1)//2 ] )/float(2) )
            
    
    
    # Your MedianFinder object will be instantiated and called as such:
    # obj = MedianFinder()
    # obj.addNum(num)
    # param_2 = obj.findMedian()

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.