LeetCode 202.Happy Number 利用存储结构或快慢指针

题目

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

思路

关键在于不是happy number则会出现数字链循环,抓住这一点,我们只需要判断当一个数不是1时,它是否在之前的计算过程出现过,若出现过则原始数不是happy number,否则继续执行各位平和操作

有两种判断方法,这题用第二种效率会更高:

  • 利用存储结构unordered_set记录出现过的数据,这种是最直接简单的解法不详细说,最后都有代码

  • 利用快慢指针判断计算过程是否有重复数出现而形成循环
      我们不断生成新的数这个过程就像在遍历一个链路。
      大家可以想一下上体育课长跑的情景。当同学们绕着操场跑步的时候,速度快的同学会遥遥领先,最后甚至会超越其他同学一圏乃至n圈——这是绕圈跑。那么如果不是绕圈跑呢?速度快的同学则会一直领先直到终点,不会再次碰到后面速度较慢的同学。
      这种思想可以用来判断单链表是否有环。如果链表存在环,就好像操场的跑道一样是一个环形一样。此时让快、慢指针都从链表头开始遍历,快指针每次向前移动两个位置,慢指针每次向前移动一个位置;如果快指针到达NULL,说明链表以NULL为结尾,没有环。如果快指针追上慢指针,则表示有环。

代码

unordered_set版本

class Solution {
public:
    bool isHappy(int n) {
        if (n <= 0) return false;

        unordered_set<int> nums;
        while (n != 1) {
            if (nums.find(n) != nums.end()) return false;

            nums.insert(n);

            int sum = 0;
            while (n) {
                sum += (n % 10) * (n % 10);
                n /= 10;
            }
            n = sum;
        }
        return true;
    }
};

快慢指针版本

class Solution {
public:
    bool isHappy(int n) {
        int slow = n;
        int fast = n;
        do{
            if( fast == 1 || next( fast ) == 1 )
                return true;
            slow = next( slow );
            fast = next( next( fast ) );
        }while( slow != fast );
        return false;
    }

    int next( int n ){
        int k = 0;
        while( n ){
            k += ( n % 10 ) * ( n % 10 );
            n /= 10;
        }
        return k;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值