当前位置:网站首页>快乐数[环类问题之快慢指针]
快乐数[环类问题之快慢指针]
2022-07-01 21:45:00 【REN_林森】
前言
分析题意,出现死循环相关问题,则属于环类问题,需用紧密联系的知识点快慢指针解决。保持快慢指针对环问题/死循环问题的敏感性。
一、快乐数

二、快慢指针
package everyday.doublePoint;
// 快乐数
public class IsHappy {
/* target:将一个数变成另一个数,按照一条固定的路径变下去,变到1就是快乐数,进入死循环就是非块乐数。 这就类似一个路径可能有环,可能无环。 最关键的地方在于判定是否有环,无环则是快乐数,有环则是非快乐数。 最直观的想法就是hash记录。 但是对于环问题,和其紧密关联的知识点就是快慢指针,如果快慢指针相碰,则有环,否则快指针走到末尾。 */
public boolean isHappy(int n) {
// 初始化快慢指针位置,快的在前,慢的再后。
int fast = getNext(n), slow = n;
// 一快一慢开始寻找。
while (fast != 1 && fast != slow) {
// fast走两步,slow走一步,要是有环必相碰,否则fast走到末尾的1.
fast = getNext(getNext(fast));
slow = getNext(slow);
}
// 看看是因为环结束,还是因为fast走到末尾结束。
return 1 == fast;
}
private int getNext(int n) {
int sum = 0;
while (n > 0) {
int mod = n % 10;
sum += mod * mod;
// 更新n
n /= 10;
}
return sum;
}
}
总结
1)保持快慢指针对环问题/死循环问题的敏感性。
参考文献
[1] LeetCode 快乐数
边栏推荐
- 为什么数字化转型战略必须包括持续测试?
- php反射型xss,反射型XSS测试及修复
- linux下清理系统缓存并释放内存
- pytest合集(2)— pytest运行方式
- 物联网rfid等
- Using closures to switch toggle by clicking a button
- Pytest Collection (2) - mode de fonctionnement pytest
- “丝路正青春 风采看福建”在闽外籍青年短视频大赛火热征集作品中
- Can you get a raise? Analysis on gold content of PMP certificate
- Smart micro mm32 multi-channel adc-dma configuration
猜你喜欢

首席信息官对高绩效IT团队定义的探讨和分析

Go - exe corresponding to related dependency
![[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial](/img/ac/655fd534ef7ab9d991d8fe1c884853.png)
[intelligent QBD risk assessment tool] Shanghai daoning brings you leanqbd introduction, trial and tutorial

pytest合集(2)— pytest運行方式

按照功能对Boost库进行分类

News classification based on LSTM model

Pytest collection (2) - pytest operation mode

pytest合集(2)— pytest运行方式

AIDL基本使用
![比较版本号[双指针截取自己想要的字串]](/img/19/4f858ffdc1281d6b8b18a996467f10.png)
比较版本号[双指针截取自己想要的字串]
随机推荐
pytest合集(2)— pytest运行方式
Do you want to make up for the suspended examination in the first half of the year? Including ten examinations for supervision engineers, architects, etc
名单揭晓 | 2021年度中国杰出知识产权服务团队
Why does blocprovider feel similar to provider?
函数基本学习之一
业务可视化-让你的流程图'Run'起来
Go — 相关依赖对应的exe
[noip2013] building block competition [noip2018] road laying greed / difference
Four methods of JS array splicing [easy to understand]
详解LockSupport的使用
[live broadcast review] the first 8 live broadcasts of battle code Pioneer have come to a perfect end. Please look forward to the next one!
Make a three digit number of all daffodils "recommended collection"
In the past 100 years, only 6 products have been approved, which is the "adjuvant" behind the vaccine competition
【生态伙伴】鲲鹏系统工程师培训
三翼鸟两周年:羽翼渐丰,腾飞指日可待
K-means based user portrait clustering model
CSDN购买的课程从哪里可以进入
中通笔试题:翻转字符串,例如abcd打印出dcba
Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
Introduction and download of the latest version of airserver2022