zoukankan      html  css  js  c++  java
  • 面试题29-数组中出现次数超过一半的值

    1. # -*- coding: utf-8 -*-
    2. """
    3. Created on Fri Mar  3 20:07:11 2017
    4. @author: zzpp220
    5. """
    6. class Morethanhalf:
    7.    def findhalf(self,lst):
    8.        if not lst:
    9.            return None
    10.        
    11.        dict={}
    12.        half=[]        
    13.        for i in lst:
    14.            dict[i]=lst.count(i)
    15.        half=[k for k ,v in dict.iteritems() if v >=len(lst)//2]
    16.        return half
    17.        
    18.    def CheckMoreThanHalf(self, numbers, length, number):
    19.        times = 0
    20.        for i in range(length):
    21.            if numbers[i] == number:
    22.                times += 1
    23.        if times*2 <= length:
    24.            return False
    25.        return True
    26.        
    27.    def MoreThanHalfNum(self, numbers):
    28.        
    29.        if numbers == None :
    30.            return 0
    31.        length = len(numbers)    
    32.        result = numbers[0]
    33.        times = 1
    34.        for i in range(1, length):
    35.            if times == 0:
    36.                result = numbers[i]
    37.                times = 1
    38.            elif numbers[i] == result:
    39.                times += 1
    40.            else:
    41.                times -= 1
    42.        if not self.CheckMoreThanHalf(numbers, length, result):
    43.            result = 0
    44.        return result
    45. solution=Morethanhalf()
    46. lst=None#[1]#[1,2,6,14,4,4,3]
    47. print solution.findhalf(lst)
    48. print solution.MoreThanHalfNum(lst)


    附件列表

    • 相关阅读:
      一些业内有名的网站收集
      WCF重载
      FCKEditor fckconfig.js配置,添加字体和大小 附:中文字体乱码问题解决
      查询第几条到第几条的数据的SQL语句
      SPOJ 9939 Eliminate the Conflict
      UVA 10534 Wavio Sequence
      HDU 3474 Necklace
      POJ 2823 Sliding Window
      UVA 437 The Tower of Babylon
      UVA 825 Walking on the Safe Side
    • 原文地址:https://www.cnblogs.com/zzxx-myblog/p/6498554.html
    Copyright © 2011-2022 走看看