【发布时间】:2015-07-20 08:33:07
【问题描述】:
我必须找到具有“N”位数字的最大“体面数字”。一个体面的数字具有以下属性:
=> 3, 5, or both as its digits. No other digit is allowed.
=> Number of times 3 appears is divisible by 5.
=> Number of times 5 appears is divisible by 3.
我的代码运行完美!但恐怕它远没有效率:
输入:
4 #number of test cases, i.e., the following 4 inputs
1
3
5
11
输出:
-1
555
33333
55555533333
我的解决方案版本:
T = int(input()) #number of test cases
def computePair(N):
multiplesOf3 = [i for i in range(N+1) if i%3 == 0]
if multiplesOf3 != [0]: #reversing a [0] results in a 'NoneType'
multiplesOf3.reverse()
multiplesOf5 = [i for i in range(N+1) if i%5 == 0]
for i in multiplesOf3:
for j in multiplesOf5:
if (i+j) == N:
return (i, j)
return -1
for testCase in range(T):
N = int(input()) #test case
result = computePair(N)
if result == -1:
print(result) #If no such combination exists return '-1'
else:
print('5' * (result[0]) + '3' * (result[1]))
我假设我的代码的时间复杂度为 O(n^2);因为有 2 个“for”循环。我希望这在 O(n) 的顺序上更有效 - 线性。
这是一个非常笼统的问题:另外,您有时间复杂性最佳实践的资源吗?我很讨厌它。
【问题讨论】:
-
如果您在 CodeReview 上重复了您的问题,请删除此问题。 IMO,这个问题纯粹是问一个更好的算法,这完全符合主题。
标签: python algorithm python-3.x big-o time-complexity