1.查找
- 关键码key与值value;
- 静态查找表与动态查找表:静态不能被改变,动态可以改变
- 平均查找长度ASL:
2.哈希表
2.1 哈希集
哈希集是集合的实现之一,它是一种存储不重复值的数据结构。头文件为<unordered_set>,基本用法如下:
unordered_set<int> hashset;
// 2. insert a new key
hashset.insert(3);
// 3. delete a key
hashset.erase(2);
// 4. check if the key is in the hash set
if (hashset.count(2) <= 0) {
cout << "Key 2 is not in the hash set." << endl;
}
// 5. get the size of the hash set
cout << "The size of hash set is: " << hashset.size() << endl;
// 6. iterate the hash set
for (auto it = hashset.begin(); it != hashset.end(); ++it) {
cout << (*it) << " ";
}
cout << "are in the hash set." << endl;
// 7. clear the hash set
hashset.clear();
2.1.1 简单题
- 存在重复元素
- 只出现一次的数字
- …
2.1.2 快乐数
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
题解:
思路:快乐数由于会不断进行拆分产生下一个数,因此必然采用while循环,关键在于跳出while循环的条件;此时,根据定义快乐数只有当其能够迭代后产生的数变成10^n时才成立,即采用该条件作为退出while循环的条件,否则一直迭代。
难受,,,我太菜了我…非得用clion调,调了10分钟才弄好
注意:n/10 > 1是错误的,n>10才对 ;得好好复习一下运算符号的优先级
bool isHappy(int n) {
//可以变为1说明,该数有且仅有一位为1,其余均为0,即该数字只能为1或者10的指数的整数
// 当n不为10的n次方时,进行迭代
//否则退出,该数为快乐数
unordered_set<int> setNum;
setNum.insert(n);
while( !isTenPower(n) ){
vector<int> nums = splitNumber(n);
n=0;
for(auto ele:nums){
n+=ele*ele;
}
// 寻找过去是否出现该值
if(setNum.count(n)==0 )
{
setNum.insert(n);
}else return false; //如果迭代过程中n值处于循环,则必然不为快乐数
}
return true;
}
// 拆分整数
vector<int> splitNumber(int num){
vector<int> res;
// 不为个位数时,逐层相除
while( num >=10){
res.push_back(num%10);
num=num/10;
}
res.push_back(num%10);
return res;
}
// 判断该数是否为10的整数次方,即判断 不断的模10最后一位是否为1
bool isTenPower(int n){
if(n==1) return true; //1也算特例
while( n>=10){
if(n%10!=0) return false;
n=n/10;
}
if(n%10!=0) return false;
return true;
}
2020/3/13
哈希表与快乐数
3881

被折叠的 条评论
为什么被折叠?



