leetcode202(Floyd判圈算法(龜兔賽跑算法))


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.

一個快樂數是這樣定義的,規則如下:由一個整數開始,之后由整數每一位數字的平方和的總和代替這個數,然后重復這個過程,直到最后是1為止,或者這個循環是一個沒有包含1的死循環。這些過程中最終結果是1的這些數被稱為快樂數。

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

 

這個題目真的我沒有想到好的思路,能想到的幾點說一下,平方的值只有從0-9這幾個數的平方,所以,定一個固定的數組一定比平方的計算要快,直接可以用數組下標取出最后的結果。

這道題難在如何判斷它是一個死循環,而且還是沒有1的。除了循環枚舉我真的沒有想到什么好的方法,我只能在想,肯定有幾種特殊的情況是遇到一定是會出現死循環的。

網上給出的解答是這樣的,具體是這樣的

int digitSquareSum(int n) {
    int sum = 0, tmp;
    while (n) {
        tmp = n % 10;
        sum += tmp * tmp;
        n /= 10;
    }
    return sum;
}

bool isHappy(int n) {
    int slow, fast;
    slow = fast = n;
    do {
        slow = digitSquareSum(slow);
        fast = digitSquareSum(fast);
        fast = digitSquareSum(fast);
    } while(slow != fast);
    if (slow == 1) return 1;
    else return 0;
}

這個算法我也是第一次見到,這我就好好研究了一番,發現這真的是一個神奇的算法。

名字叫做Floyd判圈算法(龜兔賽跑算法)

先往簡單了說,就是判斷有沒有環,定兩個起始位置一樣的指針,一個跑的慢每次跑一個循環,一個跑的快每次跑相當於跑兩個循環,一旦他們出現相同之后,那么就肯定是有環了,然后我們就看責怪環是不是1即可,這個算法最大的一個優點是時間復雜度低,空間復雜度也低,你不需要保存每一次出現的值然后和前面的值作比較。

具體算法的講解我這邊直接貼上地址,轉載自:

http://blog.csdn.net/wall_f/article/details/8780209

說實話我很喜歡這個算法,確實棒極了!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM