哈希表 快乐数

2020-06-16 11:10 更新

题目

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

  1. 输入:19
  2. 输出:true
  3. 解释:
  4. 12 + 92 = 82
  5. 82 + 22 = 68
  6. 62 + 82 = 100
  7. 12 + 02 + 02 = 1

解法一:利用哈希表特性

1.判断是否存在

  1. class Solution {
  2. public boolean isHappy(int n) {
  3. Set<Integer> set = new HashSet<>();
  4. set.add(n);
  5. while (true){
  6. n = create(n);
  7. if(n == 1)
  8. return true;
  9. if(set.contains(n))
  10. return false;
  11. set.add(n);
  12. }
  13. }
  14. private int create(int n) {
  15. int sum = 0;
  16. while (n != 0){
  17. sum += n % 10 * (n % 10);
  18. n /= 10;
  19. }
  20. return sum;
  21. }
  22. }

2.判断是否为1.否则继续做循环,重复出现则跳出循环

  1. class Solution {
  2. public boolean isHappy(int n) {
  3. Set<Integer> happySet = new HashSet();
  4. return judge(n, 0, happySet) == 1;
  5. }
  6. public int judge(int n, int happy, Set<Integer> happySet) {
  7. while(n >= 10) {
  8. int x = n % 10;
  9. n = n / 10;
  10. happy += x*x;
  11. }
  12. happy += n*n; //这个happy是经过平方和后的新数
  13. if(!happySet.add(happy)) {
  14. return happy;
  15. }
  16. return happy == 1 ? happy : judge(happy, 0, happySet);
  17. }
  18. }

3.快慢指针

  1. public boolean isHappy2(int n){
  2. int slow = n, fast = create(n);
  3. while(fast != 1){
  4. if(fast == slow) return false; // 快指针等于慢指针,这个说明在计算过程中循环了,数字之间构成了环。
  5. fast = create(create(fast));
  6. slow = create(slow);
  7. }
  8. return true;
  9. }
  10. private int create(int n) {
  11. int sum = 0;
  12. while (n != 0){
  13. sum += n % 10 * (n % 10);
  14. n /= 10;
  15. }
  16. return sum;
  17. }

python

  1. class Solution:
  2. def isHappy(self, n: int) -> bool:
  3. happy_set = set()
  4. flag = self.judge(n, 0, happy_set)
  5. return flag == 1
  6. def judge(self, n: int, happy: int, happy_set: set) -> int:
  7. while(n >= 10):
  8. x = n % 10
  9. happy += x*x
  10. n = n // 10
  11. happy += n*n #这个happy是经过平方和后新的新数
  12. if(not(happy in happy_set)):
  13. happy_set.add(happy)
  14. else:
  15. return happy
  16. return happy if happy == 1 else self.judge(happy, 0, happy_set)

4.关键点

HashSet(Collection<? extends E> c) 构造一个包含指定集合中的元素的新集合。

HashSet(int initialCapacity) 构造一个新的空集合;

背景HashMap实例具有指定的初始容量和默认负载因子(0.75)。

HashSet(int initialCapacity, float loadFactor) 构造一个新的空集合; 背景HashMap实例具有指定的初始容量和指定的负载因子。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号