【问题标题】:Decent Numbers | Help Reduce Time Complexity体面的数字 |帮助降低时间复杂度
【发布时间】:2015-07-20 08:33:07
【问题描述】:

HackerRank Problem Statement

我必须找到具有“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


【解决方案1】:

要解决这个问题,我们需要做一些观察:

  • the largest "decent number" having 'N' digits 是包含最多数字 5 的数字。其格式为 5555...3333...

  • 作为Number of times 5 appears is divisible by 3,所以我们有三种情况:

    • 如果N除以3,则没有数字3。

    • 如果N % 3 = 1,那么我们需要在结果中加上a times数字3,并且a % 3 == 1使得数字5的总数(N - a)可以被3整除,所以a % 3 == 1和@ 987654328@ -> a = 10。 (请注意,a 必须是所有有效值中的最小值)。最终结果将有(N - 10) 5 位和10 3 位。

    • 同样,如果N % 3 = 2,所以我们需要在结果中添加a times数字3,a % 3 == 2a % 5 == 0 -> a = 5;

通过这些观察,您可以在 O(1) 中对每个 N 解决这个问题。

【讨论】:

  • 显然,你可以硬编码N<9时的特殊情况。
猜你喜欢
  • 1970-01-01
  • 2011-06-15
  • 2012-07-28
  • 2016-10-07
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
相关资源
最近更新 更多