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

来源:互联网 发布:linux mint 中文 编辑:程序博客网 时间:2024/05/17 04:31

题目

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;    }};
原创粉丝点击