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)


    附件列表

    • 相关阅读:
      WINREG.H 编译出错
      WINREG.H 编译出错
      JS创建对象的几种方式
      清除radio单选框外边距
      Dragging MovieClips
      Cannot Say No
      分层提高软件系统的可测试性
      如何从技术上掌控项目?
      领导我只需要你告诉我你要做什么,怎么做让我来好吗?
      如何依据框架进行任务分解
    • 原文地址:https://www.cnblogs.com/zzxx-myblog/p/6498554.html
    Copyright © 2011-2022 走看看