当前位置:网站首页>快乐数[环类问题之快慢指针]
快乐数[环类问题之快慢指针]
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 快乐数
边栏推荐
- Qtreeview+qabstractitemmodel custom model: the third of a series of tutorials [easy to understand]
- 【单体】流辰信息I-BPSv3服务器推荐配置
- [NOIP2013]积木大赛 [NOIP2018]道路铺设 贪心/差分
- Mask wearing detection method based on yolov5
- [monomer] recommended configuration of streaming information i-bpsv3 server
- 函数基本学习之一
- MQ学习笔记
- 上半年暂停考试要补考?包含监理工程师、建筑师等十项考试
- In the past 100 years, only 6 products have been approved, which is the "adjuvant" behind the vaccine competition
- Business visualization - make your flowchart'run'up
猜你喜欢
![[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial](/img/b0/029cdea72483ed9bc8a0d66908983a.png)
[commercial terminal simulation solution] Shanghai daoning brings you Georgia introduction, trial and tutorial

Flume interview questions

Introduction and download of the latest version of airserver2022

AirServer2022最新版功能介绍及下载

MIT|256KB 内存下的设备上训练

Training on the device with MIT | 256Kb memory
![[NOIP2013]积木大赛 [NOIP2018]道路铺设 贪心/差分](/img/d1/a56231cd4eb3cc1d91d8a55048ccfe.png)
[NOIP2013]积木大赛 [NOIP2018]道路铺设 贪心/差分

并发编程系列之FutureTask源码学习笔记

详解LockSupport的使用

One of the basic learning of function
随机推荐
Introduction and download of the latest version of airserver2022
都能看懂的LIS(最长上升子序列)问题[通俗易懂]
小 P 周刊 Vol.11
详解LockSupport的使用
Fundamentals - IO intensive computing and CPU intensive computing
LIS (longest ascending subsequence) problem that can be understood [easy to understand]
Unity uses SQLite
对象内存布局
[monomer] recommended configuration of streaming information i-bpsv3 server
信标委云原生专题组组长,任重道远!
The difference between NiO and traditional IO
比较版本号[双指针截取自己想要的字串]
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
The correct way to set the bypass route
Count the number of each character in the character
统计字符中每个字符出现的个数
Electron学习(三)之简单交互操作
BlocProvider 为什么感觉和 Provider 很相似?
js如何获取集合对象中某元素列表
【MySQL】数据库优化方法