当前位置:   article > 正文

LeetCode 202. 快乐数

LeetCode 202. 快乐数

题目:

https://leetcode-cn.com/problems/happy-number/

本题关键在于如何理解题目中的【无限循环】,这里指的是规律性的重复循环,也就是一个环,所以本题旨意是求解指定的数列是否存在

题解一:哈希表

将出现过的数字全部存放在哈希表中,每次生成下一个数字时,先检测是否在哈希表中出现过,如果哈希表中已存在当前数字,证明存在环,时间复杂度:O(logn)。

  1. public boolean isHappy(int n) {
  2. Set<Integer> set = new HashSet<>();
  3. while (n != 1 && !set.contains(n)) {
  4. set.add(n);
  5. n = getValue(n);
  6. }
  7. return n == 1;
  8. }
  9. public int getValue(int n) {
  10. int res = 0;
  11. while (n != 0) {
  12. int temp = n % 10;
  13. res += temp * temp;
  14. n = n / 10;
  15. }
  16. return res;
  17. }

题解二:快慢指针法。

1.如果是快乐数,没有循环,那么快指针肯定会先到达1.

2.如果不是快乐数,即存在循环,那么快指针肯定会在某一个数字追上慢指针。

时间复杂度:O(logn)

  1. public boolean isHappy2(int n) {
  2. int slow = n;
  3. int fast = getValue(n);
  4. while (fast != 1 && fast != slow) {
  5. fast = getValue(fast);
  6. fast = getValue(fast);
  7. slow = getValue(slow);
  8. }
  9. return fast == 1;
  10. }
  11. public int getValue(int n) {
  12. int res = 0;
  13. while (n != 0) {
  14. int temp = n % 10;
  15. res += temp * temp;
  16. n = n / 10;
  17. }
  18. return res;
  19. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号