散列表

9 阅读1分钟

1、2-SUM-hash

image.png

要求 a1+a2=k,确定a1,再去找a2是否在。
用hash直接地址,及一个数组记录该下标对应元素是否在序列中出现

//我的解法
#include <bits/stdc++.h>

using namespace std;
const int Max_num = pow(10,6)+1;

int main(){
    int n, k, num;
    int count=0;          //满足条件对数
    cin >> n >> k;
    int hash_arc[Max_num] = {0};
    for(int i = 0; i<n; i++){
        cin >> num;
        hash_arc[num]++;
    }
    
    for(int i = 0; i<Max_num && i <k; i++){
        if(hash_arc[i] && hash_arc[k-i] ){
            count++;
        }
    }
    cout << count/2;
    return 0;
}

2、字符串出现次数

image.png

难点在于:如何将字符串转化为hash对应数值,以作为下标

转换公式:a2*26平方 + a1 *26 + a0;
//就是用类似10进制的26进制转换

#include <bits/stdc++.h>
using namespace std;
const int Max_num = pow(26, 3);

int to_hash(string str){
    int outcome;
    outcome = (str[0]-'A') * pow(26,2)+(str[1]-'A') * pow(26,1)+(str[2]-'A');
    return outcome;
}

int main(){
    int n, m;
    cin >> n;
    string now_str;
    string find_str;
    int hash[Max_num] = {0};
    for(int i=0; i<n; i++){
        cin >> now_str;
        hash[to_hash(now_str)]++;
    }
    //输入检测数据
    cin >> m;
    for(int i=0; i<m; i++){
        cin >> find_str;
        if(i !=0)   cout << " ";
        cout << hash[to_hash(find_str)];
    }
    return 0;
}