202. 快乐数 简单 哈希表判断 快慢指针 数学

  1. 快乐数
    编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」 定义为:

对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。

示例 1:

输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
示例 2:

输入:n = 2
输出:false

方法一:数组模拟哈希表
class Solution {
    public boolean isHappy(int n) {
        boolean st[]=new boolean [1001];
        while(true){
            if(n==1)return true;
            n=happy(n);
            if(st[n]==true)return false;
            st[n]=true;
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
方法二:快慢指针判断(弗洛伊德循环查找算法)

如果循环,快慢指针一定会相遇
慢指针速度为1,快指针速度为2

假设循环中的节点个数为n,那么这种查找法的时间和复杂度就是O(n)

class Solution {
    public boolean isHappy(int n) {
        int slow=n,fast=happy(n);
        while(true){
            if(fast==1)return true;
            if(slow==fast)return false;
            slow=happy(slow);
            fast=happy(happy(fast));
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
方法三:数学 硬编码(奇技淫巧。。。)

参考:https://leetcode.cn/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/

实际上只有一个循环:44→16→37→58→89→145→42→20→4

所以幸福数的题目要么最后等于1要么最后进入这个循环,于是可以硬编码解决(在循环中判断1和4就行)

class Solution {
    public boolean isHappy(int n) {
        while(true){
            if(n==1)return true;
            if(n==4)return false;
            n=happy(n);
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
posted @ 2022-11-17 23:01  林动  阅读(38)  评论(0编辑  收藏  举报