leetcode【202】【tag Math】Happy Number【c++版本,時間100%】

問題描述:

Write an algorithm to determine if a number n 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.

Return True if n is a happy number, and False if not.

Example: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

源碼:

首先看一下本人又笨又cuo的方法,用一個hash存下之前出現過的數字,如果出現重複的說明有環返回false,若等於1則說明滿足條件,返回1。時間上還行,空間損耗比較大。

class Solution {
public:
    bool isHappy(int n) {
        int init = n;
        unordered_set<int> help;
        help.insert(n);
        while (true){
            int tmp = 0;
            while (n!=0){
                int yu = n%10;
                tmp += yu*yu;
                n = n/10;
            }
            if (tmp == 1)     return true;
            if (help.count(tmp))    return false;
            help.insert(tmp);
            n = tmp;
        }
        return false;
    }
};

翻了一下discuss區,看到了一個大佬的做法。用了一個快慢指針的思想。快指針每次走兩步,慢指針每次走一步。直到他們重合的時候,說明可能返回false,但此時仍然有一可能就是它們都爲1,因此還要多判斷一下是否爲1。

時間100%,空間67%。

class Solution {
public:
    int next(int n){
        int tmp = 0;
        while (n!=0){
            int yu = n%10;
            tmp += yu*yu;
            n = n/10;
        }
        return tmp;
    }
    
    bool isHappy(int n) {
        int slow=n, fast=n;
        do {
            if (slow == 1)      return true;
            slow = next(slow);
            fast = next(next(fast));
        } while (slow != fast);
        if (slow == 1)      return true;
        return false;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章