算法

LeetCode题解:快乐数

2022-03-30  本文已影响0人  搬码人

题目描述

编写一个算法来判断一个数n是不是快乐数。
“快乐数”定义为:

如果n是快乐数就返回true,否则就返回false。

示例

思路方法

只需要抓住一点:按快乐数的运算方式,最后得到的数要么是1,要么就在一定范围内无限循环(得不到1)。

哈希法

class Solution {
    public int getNext(int n){
        int totalNum = 0;
        while(n!=0){
            int temp=n%10;
            n/=10;
            totalNum+= temp*temp;
        }
        return totalNum;
    }
    public boolean isHappy(int n) {
        Set<Integer> hash = new HashSet<Integer>();
        while(n>1&&!hash.contains(n)){
            hash.add(n);
            n = getNext(n);
        }
        return n==1;
    }
}

复杂度分析

双指针法

class Solution {
    public int getNext(int n){
        int totalNum = 0;
        while(n!=0){
            int temp=n%10;
            n/=10;
            totalNum+= temp*temp;
        }
        return totalNum;
    }
    public boolean isHappy(int n) {
        int slow = n;
        int fast = getNext(n);
        while(fast!=1&&fast!=slow){
            slow = getNext(slow);
            fast = getNext(getNext(fast));
        }
        return fast==1;
    }
}

复杂度分析

上一篇 下一篇

猜你喜欢

热点阅读