zoukankan      html  css  js  c++  java
  • 剑指Offer 41 数据流中的中位数

    数据流中的中位数

    如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值,那么中位数就是所有数值排序之后位于中间的数值。如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。我们使用Insert()方法读取数据流,使用GetMedian()方法获取当前读取数据的中位数。

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     def __init__(self):
     4         self.l = []
     5         self.min = 0
     6         self.max = 0
     7         self.len = 0
     8         
     9     def Insert(self, num):
    10         if self.len == 0:
    11             self.l.append(num)
    12             self.min = num
    13             self.max = num
    14         else:
    15             if num <= self.min:
    16                 self.min = num
    17                 self.l.insert(0,num)
    18             elif num >= self.max:
    19                 self.max = num
    20                 self.l.append(num)
    21             else:
    22                 for i in range(1,self.len):
    23                     if  self.l[i-1] <= num  and num <= self.l[i]:
    24                         self.l.insert(i,num)
    25                         break
    26         self.len += 1
    27         # write code here
    28     def GetMedian(self,data):
    29         if self.len == 0:
    30             return 0
    31         elif self.len == 1:
    32             return self.l[0]
    33         elif self.len == 2 :
    34             return (self.l[0] + self.l[1]) / 2.0
    35         else:
    36             result = 0
    37             if self.len % 2 == 1:
    38                 mid = self.len // 2
    39                 result = self.l[mid]
    40             else:
    41                 mid = self.len // 2
    42                 result = (self.l[mid] + self.l[mid - 1]) / 2.0
    43             return result
    44         # write code here

    字符流中第一个不重复的字符

    请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。

     1 # -*- coding:utf-8 -*-
     2 class Solution:
     3     # 返回对应char
     4     def __init__(self):
     5         self.cnts = [0] * 256
     6         self.queue = []
     7         
     8     def FirstAppearingOnce(self):
     9         return '#' if len(self.queue)==0 else chr(self.queue[0])
    10         # write code here
    11     def Insert(self, char):
    12         self.cnts[ord(char)] += 1
    13         self.queue.append(ord(char))
    14         while len(self.queue) > 0 and self.cnts[self.queue[0]] > 1:
    15             self.queue.pop(0)
    16         # write code here
  • 相关阅读:
    linux初学者-普通磁盘分区篇
    linux初学者-延迟及定时任务篇
    linux初学者-网络管理篇
    linux初学者-虚拟机联网篇
    贪吃蛇Ground Java实现(二)
    贪吃蛇 Java实现(一)
    创建异常
    IO流
    实训第一天
    Array 遍历数组
  • 原文地址:https://www.cnblogs.com/asenyang/p/11015975.html
Copyright © 2011-2022 走看看