leetcode202(Floyd判圈算法(龟兔赛跑算法))
Write an algorithm to determine if a number is "happy".
寫出一個(gè)算法確定一個(gè)數(shù)是不是快樂數(shù)。
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.
一個(gè)快樂數(shù)是這樣定義的,規(guī)則如下:由一個(gè)整數(shù)開始,之后由整數(shù)每一位數(shù)字的平方和的總和代替這個(gè)數(shù),然后重復(fù)這個(gè)過程,直到最后是1為止,或者這個(gè)循環(huán)是一個(gè)沒有包含1的死循環(huán)。這些過程中最終結(jié)果是1的這些數(shù)被稱為快樂數(shù)。
Example: 19 is a happy number
- 12 + 92 = 82
- 82 + 22 = 68
- 62 + 82 = 100
- 12 + 02 + 02 = 1
?
這個(gè)題目真的我沒有想到好的思路,能想到的幾點(diǎn)說一下,平方的值只有從0-9這幾個(gè)數(shù)的平方,所以,定一個(gè)固定的數(shù)組一定比平方的計(jì)算要快,直接可以用數(shù)組下標(biāo)取出最后的結(jié)果。
這道題難在如何判斷它是一個(gè)死循環(huán),而且還是沒有1的。除了循環(huán)枚舉我真的沒有想到什么好的方法,我只能在想,肯定有幾種特殊的情況是遇到一定是會(huì)出現(xiàn)死循環(huán)的。
網(wǎng)上給出的解答是這樣的,具體是這樣的
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; }這個(gè)算法我也是第一次見到,這我就好好研究了一番,發(fā)現(xiàn)這真的是一個(gè)神奇的算法。
名字叫做Floyd判圈算法(龜兔賽跑算法)
先往簡單了說,就是判斷有沒有環(huán),定兩個(gè)起始位置一樣的指針,一個(gè)跑的慢每次跑一個(gè)循環(huán),一個(gè)跑的快每次跑相當(dāng)于跑兩個(gè)循環(huán),一旦他們出現(xiàn)相同之后,那么就肯定是有環(huán)了,然后我們就看責(zé)怪環(huán)是不是1即可,這個(gè)算法最大的一個(gè)優(yōu)點(diǎn)是時(shí)間復(fù)雜度低,空間復(fù)雜度也低,你不需要保存每一次出現(xiàn)的值然后和前面的值作比較。
具體算法的講解我這邊直接貼上地址,轉(zhuǎn)載自:
http://blog.csdn.net/wall_f/article/details/8780209
說實(shí)話我很喜歡這個(gè)算法,確實(shí)棒極了!
總結(jié)
以上是生活随笔為你收集整理的leetcode202(Floyd判圈算法(龟兔赛跑算法))的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Docker中运行Dubbo应用
- 下一篇: buildroot mysql