编程集训 day01 hash table
- 对于hash table 的理解(不知道理解是否正确,希望有大神指点一二):
第一次接触hash table, 所以查找了很多资料(后面有放链接)试图理解:Hash table 可以加快数据的查找速度,节省时间;
数据存储:将字符串中的每个字符转换成ASCII码->所有数字求和->求得的结果÷存储空间->取余并存放相应位置
1.0. LeetCode #1. two sumLeetCode #1. two sum
1.1. solution
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> hash; //create hash table
vector<int> result;
int i,key;
for(i=0;i<nums.size();i++)
{
key=target-nums[i];
if(hash.find(key)!=hash.end()) //If the result was found, insert it and return.
{
result.push_back(hash[key]);
result.push_back(i);
return result;
}
hash[nums[i]]=i;
}
return result;
}
};
1.2 Screenshot
2.0. LeetCode #202. Happy Number
2.1. solution:
#include <math.h>
class Solution {
public:
bool isHappy(int n) {
map<int,bool> table;
table[n] = 1;
int num = 0;
while(n != 1)
{
while(n){
num += pow((n%10),2);
n = n/10;
}
if(table[num])
break;
else{
table[num]=1; // if the happy number did not be found, continue.
n = num;
num = 0;
}
}
return n;
}
};
2.2 screenshot
resources:
“How to create a hash table in C++”, https://www.youtube.com/watch?v=y_xnyjs9gcc
“What is a HashTable Data Structure - Introduction to Hash Tables , Part 0”, https://www.youtube.com/watch?v=MfhjkfocRR0
“Hash Tables and Hash Functions”, https://www.youtube.com/watch?v=KyUTuwz_b7Q
哈希表,https://zh.wikipedia.org/wiki/哈希表
“Basic of hash tables”, https://www.hackerearth.com/zh/practice/data-structures/hash-tables/basics-of-hash-tables/tutorial/