【问题标题】:Time Limit exceeded in python solutionpython解决方案中超出时间限制
【发布时间】:2019-12-13 08:07:19
【问题描述】:

我试图解决 Leetcode 问题 Happy Number,但我似乎陷入了一个奇怪的 Time Limit Exceeded Error。

我的代码:

class Solution:
    def isHappy(self, n: int) -> bool:
        def simu(n):
            sums = 0
            while n>0:
                s = n%10
                n = n//10
                sums=sums+(s**2)
            if sums != 1:
                simu(sums)
            return True
        while True:
            try:
                return simu(n)
            except RecursionError:
                return False

知道如何克服这个问题吗?

【问题讨论】:

  • 数字不满意的情况是递归应该以相同的数字结束。至少我是这么认为的,所以也许你的递归需要很长时间才能遇到递归错误。
  • 如果数字不满意,该问题不会要求返回任何内容,但我仍然使用除了 RecursionError 之外的错误处理。
  • 嗯,这意味着暴力破解方法对于 Leetcode 来说太慢了。您可能需要考虑如何通过单独查看数字来简化数学解决方案。
  • 所以你可以看出,如果任何数字返回到它自己,这意味着它不快乐。而且由于模式重复,我们可以估计在达到一些数字重复之前会有一个有限序列。因此,我认为您不会通过保留比较器来面临内存问题。如果你想有一个解决方案,但不确定它是否通过了 leetcode
  • while True: 不是必须的

标签: python python-3.x error-handling


【解决方案1】:

尝试直到获得RecursionError 是一个非常糟糕的主意。相反,我能想到的一种解决方案是,跟踪以前失败的号码,并在你得到一个已经失败的号码后立即停止进一步的尝试。因为,你肯定知道同样的事情会再次发生。

class Solution:
    def transform(self, n: int) -> int:
        s = 0
        while n > 0:
            d = n % 10
            s += d * d
            n = n // 10
        return s

    def isHappy(self, n: int) -> bool:
        failed_hist = set()  # maybe you can preload this with some already known not-happy numbers
        while n not in failed_hist:  # continue as long as `n` has not failed before
            if n == 1:
                return True
            failed_hist.add(n)  # remember this failed !
            n = self.transform(n)  # transform `n` to it's next form
        return False  # loop broke, i.e. a failed `n` occured again

这个想法是展示一个没有暴力破解的解决方案。也许可以有更好的解决方案,例如如果那些快乐的数字有一些特殊的数学属性等等......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2021-03-23
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多