Title Description
How to get the median of a data stream? If the numerical value is read from the odd data stream, then the median value is located in the middle of all values after sorting. If an even number value is read out from the data stream, then the median is the average of two numbers after all intermediate values of order. We use the Insert () method to read the data stream, using GetMedian () method to get the current median data is read.
Thinking
Each inserted, by dichotomy, the value inserted in the correct position.
The median time every acquisition, need only determines the length of the array is odd or even enough
ps: python2 inside, two integers and returns an integer. So we need to add a 0.0, then in addition to
class Solution:
numbers = []
def Insert(self, num):
i = 0
j = len(self.numbers) - 1
while i < j:
mid = int((i+j)/2)
if self.numbers[mid] < num:
i = mid+1
elif self.numbers[mid] > num:
j = mid
else:
i = mid
j = mid
self.numbers.insert(i,num)
def GetMedian(self,x):
leng = len(self.numbers)
if leng % 2 == 1:
return self.numbers[int(leng/2)]
else:
ans = (self.numbers[int(leng/2)] + self.numbers[int(leng/2 -1)] + 0.00)/2
return ans