leetcode 202. Happy Number | 循环检测

Description

Write an algorithm to determine if a number is “happy”.

A 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, and 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 numbers.

Example: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

My solution

class Solution {
public:
    bool isHappy(int n) {
        int sum;
        int rear;
        vector<int> set;
        while (n) {
            set.push_back(n);
            sum = 0;
            while (n) {
                rear = n % 10;
                sum += rear * rear;
                n /= 10;
            }
            n = sum;
            if (n == 1) return true;
            // 这里有待改进
            for (int i = 0; i < set.size(); i++) {
                if (n == set[i]) return false;
            }
        }
    }
};

问题关键地方是在陷入循环的时候跳出来, 自然的想法是开辟一个数组, 存储出现过的值, 对于每个新生成的数值, 检查数组中是否已经存在该值. 我的代码中采取的方式效率较低. discuss中表示这一步替换成Hash方式!! 类似于python中的dict形式.

参考如下:

public boolean isHappy(int n) {
    Set<Integer> inLoop = new HashSet<Integer>();
    int squareSum,remain;
    while (inLoop.add(n)) {
        squareSum = 0;
        while (n > 0) {
            remain = n%10;
            squareSum += remain*remain;
            n /= 10;
        }
        if (squareSum == 1)
            return true;
        else
            n = squareSum;

    }
    return false;

}

Discuss

发现一个神思路: 循环检测, 其实就等同于图中的环的检测. 之前做链表中环的检测做法是用两个指针, 一个walker, 一个runner(或者slower和faster), 这里再次利用这个方式(时间换取空间), 形成如下思路:

I see the majority of those posts use hashset to record values. Actually, we can simply adapt the Floyd Cycle detection algorithm. I believe that many people have seen this in the Linked List Cycle detection problem. The following is my code:

int digitSquareSum(int n) {
    int sum = 0, tmp;
    while (n) {
        tmp = n % 10;
        sum += tmp * tmp;
        n /= 10;
    }
    return sum;
}

bool isHappy(int n) {
    int slow, fast;
    slow = fast = n;
    do {
        slow = digitSquareSum(slow);
        fast = digitSquareSum(fast);
        fast = digitSquareSum(fast);
    } while(slow != fast);
    if (slow == 1) return 1;
    else return 0;
}

// 注意!! 
// 上述代码采用do-while结构,如果直接用while, 因为初始值原因, 很尴尬!!
// 用如下的方式略臃肿...
// 这个细节很微妙
while(walker!=1){
    walker = cal(walker);
    runner = cal(runner);
    runner = cal(runner);
    if(walker==runner) break;
}
return walker==1;


细想来, 可以把每次运算的结果视为一个状态, 整个计算流程实际上就是不同状态之间的转换, 状态转换看起来就是图的形式, 故而可以联想到链表中环路检测方法.

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值