赞
踩
https://leetcode-cn.com/problems/happy-number/
本题关键在于如何理解题目中的【无限循环】,这里指的是规律性的重复循环,也就是一个环,所以本题旨意是求解指定的数列是否存在环。
将出现过的数字全部存放在哈希表中,每次生成下一个数字时,先检测是否在哈希表中出现过,如果哈希表中已存在当前数字,证明存在环,时间复杂度:O(logn)。
- public boolean isHappy(int n) {
- Set<Integer> set = new HashSet<>();
- while (n != 1 && !set.contains(n)) {
- set.add(n);
- n = getValue(n);
- }
-
- return n == 1;
- }
-
- public int getValue(int n) {
- int res = 0;
- while (n != 0) {
- int temp = n % 10;
- res += temp * temp;
- n = n / 10;
- }
-
- return res;
- }

1.如果是快乐数,没有循环,那么快指针肯定会先到达1.
2.如果不是快乐数,即存在循环,那么快指针肯定会在某一个数字追上慢指针。
时间复杂度:O(logn)
- public boolean isHappy2(int n) {
- int slow = n;
- int fast = getValue(n);
- while (fast != 1 && fast != slow) {
- fast = getValue(fast);
- fast = getValue(fast);
- slow = getValue(slow);
- }
-
- return fast == 1;
- }
-
- public int getValue(int n) {
- int res = 0;
- while (n != 0) {
- int temp = n % 10;
- res += temp * temp;
- n = n / 10;
- }
-
- return res;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。