用双端队列构建一个有序的数组,再返回该有序数组中中间元素的平均值。
# -*- coding:utf-8 -*-
from collections import deque
class Solution:
def __init__(self):
self.order_list = deque()
def Insert(self, num):
# write code here
if not self.order_list:
self.order_list.append(num)
elif num >= self.order_list[-1]:
self.order_list.append(num)
elif num <= self.order_list[0]:
self.order_list.appendleft(num)
else:
for i in range(len(self.order_list) - 1):
if self.order_list[i] <= num and self.order_list[i + 1] >= num:
self.order_list.insert(i + 1, num)
break
def GetMedian(self):
# write code here
len_list = len(self.order_list)
mid_right = self.order_list[int(len_list / 2)]
mid_left = self.order_list[int((len_list - 1) / 2)]
return round((mid_right + mid_left) / 2, 2)