LeetCode 202. Happy Number - 一道被标注为easy其实不easy的题

Write an algorithm to determine if a number n is happy.

happy number is a number defined by the following process:

  • Starting with any positive integer, replace the number by the sum of the squares of its digits.
  • Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1.
  • Those numbers for which this process ends in 1 are happy.

Return true if n is a happy number, and false if not.

Example 1:

Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Example 2:

Input: n = 2
Output: false

Constraints:

  • 1 <= n <= 231 - 1

解法1:

看完题目直观的解法是一直计算下去直到等于1停止。难点是如果一直不等于1,那应该什么时候停止呢。我们知道永不停止有两种情况:

1. 进入一个环后无限循环,这种情况好判断,只要后面遇到前面出现过的数字,那就说明是一个环。

2. 数字一直变大直到无穷大。其实这种情况不会出现,我们来看一个例子,一个10位的数最大的就是9999999999,那它的下一个数就是(9*9)*10 = 810变成一个3位数;3位数最大的是999,下一个数是81 * 3 = 243。因此可以得到一个结论,到达3位数之后就不可能再变成4位以上的数,也就不可能变成无穷大。

这样题目就可以简化为判断最终是到达1还是进入一个环。

class Solution:
    def isHappy(self, n: int) -> bool:
        seen = set()
        
        while n > 1 :
            if n in seen :
                return False
            
            seen.add(n)

            tmp = 0
            while n > 0 :
                tmp += (n % 10) ** 2
                n //= 10
            n = tmp
            
        return True

这题时间复杂度计算也是个难点,时间复杂度取决于位数(一个数的位数lg(n)),对于数n第一轮时间是lg(n),另外我们知道随着循环进行位数降的很快。

因此这种解法的时间和空间复杂度都是O(lg(n))

解法2:

根据解法一的分析,我们其实是去判断是否存在一个环,这就跟另外一道题(141. Linked List Cycle)很像,判断一个链表里是否存在一个环。因此这道题也可以相同方法即快慢指针的方法。

class Solution:
    def isHappy(self, n: int) -> bool:
        def getNext(n) :
            nextNum = 0
            while n > 0 :
                nextNum += (n % 10) ** 2
                n //= 10
            return nextNum
        
        slow = n
        fast = getNext(n)
        
        while fast > 1 and slow != fast:
            slow = getNext(slow)
            fast = getNext(getNext(fast))

        return fast == 1

空间复杂度变成了O(1)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值