Simplest Python without using heapq


  • 0
    W
    class MedianFinder:
        def __init__(self):
            """
            Initialize your data structure here.
            """
            self.nums, self.median_index = [], -1
    
        def addNum(self, num):
            """
            Adds a num into the data structure.
            :type num: int
            :rtype: void
            """
            bisect.insort_left(self.nums, num)
            if len(self.nums) % 2 == 1:
                self.median_index += 1
    
        def findMedian(self):
            """
            Returns the median of current data stream
            :rtype: float
            """
            if len(self.nums) % 2 == 0:
                return (self.nums[self.median_index] + self.nums[self.median_index + 1]) / 2.0
            else:
                return self.nums[self.median_index]
    

Log in to reply
 

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