《LeetCode力扣练习》代码随想录——哈希表(快乐数---Java)

《LeetCode力扣练习》代码随想录------哈希表(快乐数---Java)



刷题思路来源于 代码随想录

202. 快乐数
Set哈希表------空间复杂度: O(logn)
java 复制代码
class Solution {
    public boolean isHappy(int n) {

        if(n==1){
            return true;
        }

        Set<Integer> hashSet=new HashSet<>();
        hashSet.add(n);

        while(n!=1){

            n=getSum(n);

            if(hashSet.contains(n)){
                return false;
            }

            hashSet.add(n);

        }

        return true;

    }

    private int getSum(int n){

        int result=0;

        while(n!=0){

            int temp=n%10;
            result=result+(temp*temp);
            n=n/10;

        }

        return result;

    }
}
快慢指针------空间复杂度: O(1)
java 复制代码
class Solution {
    public boolean isHappy(int n) {

        if(n==1){
            return true;
        }

        int slow=getSum(n);
        int fast=getSum(getSum(n));

        while(slow!=fast){

            if(fast==1){
                return true;
            }

            slow=getSum(slow);
            fast=getSum(getSum(fast));

        }

        return fast==1?true:false;

    }

    private int getSum(int n){

        int result=0;

        while(n!=0){

            int temp=n%10;
            result=result+(temp*temp);
            n=n/10;

        }

        return result;

    }
}

相关推荐
爱敲键盘的猴子9 分钟前
深入理解 Java HashMap
java·hashmap
霸道流氓气质9 分钟前
Java开发者AI编程常用MCP、Skills、Rules全景汇总
java·开发语言·ai编程
天涯醉青楼21 分钟前
Spring Boot 接口返回 Bean 时字段名“变形”的深度剖析与解决方案
java
步行cgn38 分钟前
MyBatis 高级映射与延迟加载完全指南
java·tomcat·mybatis
thefool11226639 分钟前
从中序与后序遍历序列构造二叉树
java
吴声子夜歌1 小时前
Java面试题——JVM(二)
java·开发语言·jvm
CRMEB1 小时前
商城大促活动策划全流程:从定目标到复盘四阶段
java·开发语言·人工智能·ai·开源·php
denglinqings1 小时前
Java开发从入门到精通所有课程
java·开发语言
星空1 小时前
maven镜像
java·maven
speop1 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展