判断一个数是否是开心数。
定义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