题解:数组中有一个数字出现的次数超过数组长度的一般,请找出这个数字
def MoreThanHalf(numbers): len1 = len(numbers) if len1 == 0: return 0 res = numbers[0] #初始值 count = 1 #次数 #遍历每一个元素,并记录次数;若与前一个元素相同,则次数加1,否则次数减1 for i in range(1,len1): if count == 0: #更新result的值为当前元素,并置次数为1 res = numbers[i] count = 1 elif numbers[i] == res: count += 1 #相同则加1 elif numbers[i] != res: count -= 1 #不相同则减1 #判断res是否符合条件,即出现次数大于数组长度的一半 counts = 0 for j in range(len1): if numbers[j] == res: counts += 1 if counts > len1//2: return res else: return 0 print(MoreThanHalf([1,1,1,1,2,3])) print(MoreThanHalf([1,2,2,2,3])) print(MoreThanHalf([1,3,4,3,3,3,2,3]))