[2016/12/8]happy number:application of Floyd's Cycle Detection Algorithm
来源:互联网 发布:在家网络兼职招聘 编辑:程序博客网 时间:2024/06/05 18:18
题目大意
求一个数是不是happy number(定义戳这里)
我的思路
数字如果不是happy number,就会一直被困在循环里,因为会出现同一个数字出现两次的情况。直接的思路是用set,如果一个数字出现了两次,就返回false。
别人的思路
我的做法空间复杂度略高。看了下面别人的解,空间复杂度仅为N1。大致就是设立快慢两个指针,如果存在环,两个指针一定会相遇。
参考:Floyd’s Cycle Detection Algorithm
别人的代码
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); if(fast == 1) return 1; } while(slow != fast); return 0;
0 0
- [2016/12/8]happy number:application of Floyd's Cycle Detection Algorithm
- Floyd's Cycle Detection Algorithm
- Detect Cycle in a linked list (Floyd’s Cycle Detection Algorithm)
- Floyd's cycle-finding algorithm
- 【Leetcode Algorithm】Happy Number
- Floyd判圈算法(龟兔赛跑算法, Floyd's cycle detection)及其证明
- Floyd算法——Cycle detection
- Harry Potter’s Exam (an application of Dijkstra algorithm)
- floyd's cycle detect算法
- Algorithm of Contour Detection Improvement
- Floyd’s Algorithm 弗洛伊德算法
- No.4 happy number floyd判圈法
- Cycle detection——Floyd判圈算法
- Algorithm of Contour Detection Improvement (2)
- zoj 3232 It's not Floyd Algorithm
- zoj3232 It's not Floyd Algorithm
- Algorithm of poisson random number
- 202. Happy Number (tortoise and the hare algorithm)
- 第三方绘图控件 AChartEngine 浅析
- 三角形的外接圆半径
- 30 leetcode - Search Insert Position
- Android USB Camera(2) : UVC协议分析
- 了解手机CPU
- [2016/12/8]happy number:application of Floyd's Cycle Detection Algorithm
- Billboard
- 封装继承txt
- 图片抖动的效果(修改后)
- 揭开Socket编程的面纱
- 稀疏编码器(Sparse Encoder)
- 把字符串转换成整数
- 基于SpringMVC封装常用的CRUD操作
- 点赞 数据库设计