Python 3.x 您将得到一个由N个整数组成的数组。您的任务是查找奇数在数组中重复的最大次数
您将得到一个由N个整数组成的数组。您的任务是查找奇数在数组中重复的最大次数 样本输入: 十二, 1112212211 样本输出: 四,Python 3.x 您将得到一个由N个整数组成的数组。您的任务是查找奇数在数组中重复的最大次数,python-3.x,Python 3.x,您将得到一个由N个整数组成的数组。您的任务是查找奇数在数组中重复的最大次数 样本输入: 十二, 1112212211 样本输出: 四, 我已经尝试了上述方法,但是对于输入案例,它返回6,因为您在else子句中重置了count,这是错误的,因为每次看到新的奇数时都需要重置count。此外,您需要在每次计算c后检查fc,而不仅仅是在最后。 这是您的代码修复 c = 0 fc = 0 for i in range(n): if arr[i] % 2 != 0: c = 0
我已经尝试了上述方法,但是对于输入案例,它返回6,因为您在
else
子句中重置了count,这是错误的,因为每次看到新的奇数时都需要重置count。此外,您需要在每次计算c
后检查fc
,而不仅仅是在最后。
这是您的代码修复
c = 0
fc = 0
for i in range(n):
if arr[i] % 2 != 0:
c = 0
temp = arr[i]
c += 1
for j in range(i + 1, n):
if arr[j] == temp:
c += 1
else:
print(c)
break
if c > fc:
fc = c
print(fc)
这里有一个更好的方法,它只遍历一次数字列表
index = 0
maxCount = 0
currCount = 0
while index < len(arr):
if arr[index]%2 == 1:
currCount = 0
currCount += 1
index += 1
while index < len(arr) and arr[index]%2 == 1:
currCount += 1
index+=1
if currCount > maxCount:
maxCount = currCount
index+=1
print(maxCount)
index=0
最大计数=0
currCount=0
当指数maxCount:
maxCount=currCount
指数+=1
打印(最大计数)
最大重复奇数是否需要连续?
index = 0
maxCount = 0
currCount = 0
while index < len(arr):
if arr[index]%2 == 1:
currCount = 0
currCount += 1
index += 1
while index < len(arr) and arr[index]%2 == 1:
currCount += 1
index+=1
if currCount > maxCount:
maxCount = currCount
index+=1
print(maxCount)