当前位置:网站首页>快乐数[环类问题之快慢指针]
快乐数[环类问题之快慢指针]
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 快乐数
边栏推荐
- [STM32] stm32cubemx tutorial II - basic use (new projects light up LED lights)
- 【直播回顾】战码先锋首期8节直播完美落幕,下期敬请期待!
- IDA动态调试apk
- Four methods of JS array splicing [easy to understand]
- MQ学习笔记
- Significance and measures of security encryption of industrial control equipment
- js如何获取集合对象中某元素列表
- One of the basic learning of function
- Fundamentals - IO intensive computing and CPU intensive computing
- 三翼鸟两周年:羽翼渐丰,腾飞指日可待
猜你喜欢

名单揭晓 | 2021年度中国杰出知识产权服务团队

Mask wearing detection method based on yolov5

K-means based user portrait clustering model

Training on the device with MIT | 256Kb memory

【深度学习】利用深度学习监控女朋友的微信聊天?

Pytest collection (2) - pytest operation mode

IDA动态调试apk

小 P 周刊 Vol.11

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

I received a letter from CTO inviting me to interview machine learning engineer
随机推荐
K-means based user portrait clustering model
旁路由设置的正确方式
Is PMP certificate really useful?
MySQL系列之事务日志Redo log学习笔记
基于K-means的用户画像聚类模型
【生态伙伴】鲲鹏系统工程师培训
MySQL清空表数据
PHP reflective XSS, reflective XSS test and repair
按照功能对Boost库进行分类
The leader of the cloud native theme group of beacon Committee has a long way to go!
【juc学习之路第9天】屏障衍生工具
Make a three digit number of all daffodils "recommended collection"
MIT|256KB 内存下的设备上训练
Classify boost libraries by function
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
详解Volatile关键字
mysql 学习笔记-优化之SQL优化
灵动微 MM32 多路ADC-DMA配置
Electron学习(三)之简单交互操作
多种智能指针