題目:
編寫一個算法來判斷一個數是不是 “快樂數”。
一個 “快樂數” 定義為:對于一個正整數,每一次将該數替換為它每個位置上的數字的平方和,然後重複這個過程直到這個數變為 1,也可能是無限循環但始終變不到 1。如果可以變為 1,那麼這個數就是快樂數。
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
示例:
輸入: 19
輸出: true
解釋:
1^2+ 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
解題思路:
求每個位上的數字平方和,判斷是否為 1,如果不為 1 則繼續求該數每位的平方和。
如例題中求和:19 -> 82 -> 68 ->100 ->1 ->1 -> 1 ......
不管是否為快樂數,該數最終必定進入一個循環。進入循環體的入口結點數字為 1,則該數為快樂數,否則不是快樂數。是以這道題就變成了 求有環連結清單的入環節點,這類似之前做過的另一道題:
環形連結清單 2同樣,可以用
環形連結清單2
中的兩種方法找到入環節點。
其實快樂數有一個已被證明的規律:
不快樂數的數位平方和計算,最後都會進入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循環體。
是以該題可以用遞歸來解,基線條件為
n < =4
,滿足基線體條件時,如果
n=1
則原數為快樂數,否則不是。
哈希表解題:
Java:
class Solution {
public boolean isHappy(int n) {
HashSet<Integer> hashSet = new LinkedHashSet<>();//哈希表記錄數位平方和計算過程中的每個數
while (!hashSet.contains(n)) {
hashSet.add(n);
int sum = 0;
while (n > 0) {//計算數位平方和
sum += (n % 10) * (n % 10);
n /= 10;
}
n = sum;//n 為數位平方和
}
return n == 1;
}
}
Python:
class Solution:
def isHappy(self, n: int) -> bool:
hashSet = set(1) #哈希集合内置1,可減少一次循環
while n not in hashSet:
hashSet.add(n)
n = sum(int(i)**2 for i in str(n)) #py可以直接轉乘字元串周遊每個字元計算
return n == 1
遞歸解題:
class Solution {
public boolean isHappy(int n) {
if (n <= 4) return n == 1;//基線條件
int sum = n, tmp = 0;
while (sum > 0) {
tmp += (sum % 10) * (sum % 10);
sum /= 10;
}
return isHappy(tmp);//遞歸調用
}
}
class Solution:
def isHappy(self, n: int) -> bool:
return self.isHappy(sum(int(i)**2 for i in str(n))) if n > 4 else n == 1 #一行尾遞歸
快慢指針解題:
Java:
class Solution {
public boolean isHappy(int n) {
int slow = n, fast = helper(n);
while (slow != fast) {//條件是快慢指針不相遇
slow = helper(slow);
fast = helper(fast);
fast = helper(fast);//快指針一次走兩步(計算兩次)
}
return slow == 1;
}
private int helper(int n) {//計算數位平方和輔助函數
int sum = 0;
while (n > 0) {
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
}
Python
class Solution:
def isHappy(self, n: int) -> bool:
slow, fast = n, self.helper(n)
while slow != fast:
slow = self.helper(slow)
fast = self.helper(fast)
fast = self.helper(fast)
return slow == 1
def helper(self, n: int) -> int:
return sum(int(i)**2 for i in str(n))
tips:
就這道題而言,應該用快慢指針的方法。雖然不管是否為快樂數最終都會進入循環體,但是計算數位和的過程得到的每個數總量 理論上是可以非常大的,這就可能導緻存儲的哈希集合長度過大或遞歸深度太深,空間複雜度不可預測(不會超過整型範圍)。快慢指針解題,每次值儲存兩個值,空間複雜度為 1。
歡迎關注微.信.公.衆.号:愛寫Bug
