• 剑指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
  • 相关阅读:
    HTML转义字符
    网站项目开发经验总结
    SQL SERVER事务处理
    5种方法在mac系统修改hosts文件
    用MPMoviePlayerController做在线音乐播放
    UISearchBar的使用心得
    10 个免费的 C/C++ 集成开发环境
    TableView有些属性的修改只能在init里面
    UIScrollView的正确使用方法
    设置UIView阴影shadow 边框 边框颜色
  • 原文地址:https://www.cnblogs.com/asenyang/p/11015975.html
Copyright © 2020-2023  润新知