运行时间:27ms
占用内存:5728k
用counter很容易实现
# -*- coding:utf-8 -*-
from collections import Counter
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if not numbers:
return 0
n = len(numbers)
count = Counter(numbers)
for i in numbers:
if count[i]>n/2:
return i
return 0
——————————————————————————————
标准答案没有用到字典
如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。
和另外一种思路一样:
采用用户“分形叶”思路(注意到目标数 超过数组长度的一半,对数组同时去掉两个不同的数字,到最后剩下的一个数就是该数字。如果剩下两个,那么这两个也是一样的,就是结果),在其基础上把最后剩下的一个数字或者两个回到原来数组中,将数组遍历一遍统计一下数字出现次数进行最终判断。
自我理解:
当长度为奇数,减掉一对一对不同的数之后,剩下的一定是目标数字(如果存在目标数字);
当长度为偶数,减掉一对一对不同的数之后,剩下的两个里面,必定都是目标数字(如果只有一个或者0个,则是等于或小于一半)
运行时间:28ms
占用内存:5740k
# -*- coding:utf-8 -*-
from collections import Counter
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
if not numbers:
return 0
n = len(numbers)
result = numbers[0]
count = 1
for i in range(1,n):
if count==0:
result = numbers[i]
if numbers[i]==result:
count+=1
else:
count-=1
count = 0
for i in numbers:
if i==result:
count += 1
if count>n/2:
return result
else:
return 0