马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这是一道程序填空题,题目要求:给定一个长度为n数列a,如果数列a中存在一个元素值的数量大于n/2,即存在一个数的数量超过一半,则返回1,否则返回0.题目要求用分治法处理,时间复杂度为o(nlogn)
比如输入:
5
1 2 2 3 4
返回0
输入:
5
1 2 2 2 3 (存在一个2的数量大于数列总数的一半)
返回1
题目填充框架:# Uses python3
import sys
def get_majority_element(a, left, right):
if left == right:
return -1
if left + 1 == right:
return a[left]
#write your code here
return -1
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element(a, 0, n) != -1:
print(1)
else:
print(0)
我的思路是:
如果存在一个数超过总数的一半,那么把这个数列分成两半,则其中一半必有这个数同样是这一半的过半数,依此递归合拢。
我的代码如下:#Users python3
__Author__ = 'Redleafage Zhang'
import sys
def get_majority_element(a, left, right):
list = []
if left == right:
return -1
if left + 1 == right:
return a[left]
#write your code here
mid = (left+right) // 2
major_l = get_majority_element(a,left,mid)
major_r = get_majority_element(a,mid+1,right)
if major_l == major_r:
return major_l
else:
if a.count(major_l) > right//2:
return major_l
if a.count(major_r) > right//2:
return major_r
return -1
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element(a, 0, n) != -1:
print(1)
else:
print(0)
这个代码测试的结果没问题,但是无法通过测验,提示我超时:
Failed case #11/21: time limit exceeded (Time used: 9.96/5.00, memory used: 21278720/536870912.)
请教各位鱼油,我该如何优化这个代码呢?非常感谢! |