编程集训 day01 hash table

  1. 对于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/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值