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