《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;

    }
}

相关推荐
Zane199414 分钟前
单例线程安全、生产者消费者、死锁:并发面试三连问串讲
java·后端
云烟成雨TD1 小时前
Micrometer 系列【42】链路追踪:Span 体系 | 核心 API
java·链路追踪·micrometer
Gorway1 小时前
理解 Spring 依赖注入:从构造器注入到集合与条件 Bean
java·后端
LiLiYuan.1 小时前
【字符串常量池】
java·开发语言·面试
Sylvia33.1 小时前
从轮询到推送:足球数据API架构演进与火星数据技术拆解
java·服务器·网络·python·websocket·架构
cfm_29142 小时前
高并发系统缓存全解
java·缓存
Ghost Face...2 小时前
龙芯Docker全流程:安装到离线迁移实战
java·docker·eureka
16月6日-晴2 小时前
Java面向对象进阶—static
java·开发语言
xiaohaiAIgeo2 小时前
【2026年】ASHRAE 110与EN 14175通风柜测试标准对比:进口与国产品牌性能差距
java·前端·数据库·科普知识
meilindehuzi_a3 小时前
TypeScript面试题:interface 与 type:相同点、核心区别与选择指南
java·ubuntu·typescript