zoukankan      html  css  js  c++  java
  • OJ练习39——T202 Happy Number

    判断一个数是否是开心数。

    定义happy number:

    循环求各位数的平方和,直到结果是1,则是开心数,否则不是。

    eg:19是开心数——

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

    【思路】

    看似简单的一道题,循环求各位的平方和很好写出,但是循环的终结没办法表示,什么时候返回false呢?

    题目中说:or it loops endlessly in a cycle which does not include 1

    看别人算法:用哈希表存储已经出现过的数字,如果重复出现,则说明形成一个环,可判断不是开心数。

    【other code】

    bool isHappy(int n) {
            
            if (n < 1)
                return false;
            if (n == 1)
                return true;
            unordered_set<int> showedNums;
            showedNums.insert(n);
    
            while(true)
            {
                int s = 0;
                while(n)
                {
                    s += (n % 10) * (n % 10);
                    n = n / 10;
                }
    
                if (s == 1)
                    return true;
                else if (showedNums.find(s) != showedNums.end())
                    return false;
                n = s;
                showedNums.insert(s);
            }
        
        }

    【结果】耗时9ms,排名靠前。

    【learning】

    哈希表:unordered_set

    散列容器(hash container):
     通常比二叉树的存储方式可以提供更高的访问效率.
    #include <boost/unordered_set.hpp>
    #include <boost/unordered_map.hpp>
    using namespace boost;

    (实践:下载安装boost之后,有include文件下的boost文件夹需要放在D:Program FilesMicrosoft Visual Studio 10.0VCinclude下,在工程中写为:

    #include <boost/unordered/unordered_set.hpp>
    using namespace boost;)

    散列集合简介:
     unordered库提供两个散列集合类unordered_set和unordered_multiset,STLport也提供hash_set和 hash_multiset,它们的接口,用法与stl里的标准关联容器set/multiset相同,只是内部使用散列表代替了二叉树实现,因此查找复 杂度由数降为常数。

    unordered_set简要声明:
    template<class Key, class Hash = boost::hash<Key>,
     class Pred = std::equal_to<Key>,
     class Alloc = std::allocator<Key>>
    class unordered_set;

    与std::set相比,unorder_set的模板增加了一个计算散列值的模板类型参数,通 常是boost::hash,最好不要去改变它,另外比较 谓词参数使用std::equal_to<>,而不是set中的less<>,这是因为散列容器不需要保持有序。

    see more:http://blog.csdn.net/mmzsyx/article/details/8240071

  • 相关阅读:
    oracle 巡检脚本(自动化) 规格严格
    应用版日常linux系统巡检shell脚本 规格严格
    linux系统巡检脚本 规格严格
    超级详细RPM 规格严格
    项目管理纪实一:需求调研日志
    其实你不懂程序员
    Silverlight同步(Synchronous)调用WCF服务
    GeoServer地图开发解决方案(一):环境搭建篇
    新年新起点荣获2011年度Silverlight方向Microsoft® MVP奖
    工作中发现 VC 通过 Flex 访问 FusionChart for FLEX 当VC端的驱动数据串过长时,会出现 No Data to Display错误
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4475602.html
Copyright © 2011-2022 走看看