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

    }
}

相关推荐
NE_STOP8 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园8 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆8 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz9 小时前
Maven依赖冲突
java·服务器·maven
swordbob9 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯9 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网9 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠9 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
源分享9 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Flittly9 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring