解决哈希冲突的两种方法
开放寻址法:
#include <bits/stdc++.h>
using namespace std;
const int null = 0x3f3f3f3f, N = 200003;
int h[N];
int n;
int find(int x) {
int k = (x % N + N) % N;
while (h[k] != null && h[k] != x) {
++k;
if (k == N) k = 0;
}
return k;
}
int main() {
cin >> n;
memset(h, 0x3f, sizeof h);
while (n--) {
char op[2];
int x;
cin >> op >> x;
if (*op == 'I') h[find(x)] = x;
else {
if (h[find(x)] != null) puts("Yes");
else puts("No");
}
}
return 0;
}
拉链法:
#include<bits/stdc++.h>
using namespace std;
#define N 100003
int n, idx;
int h[N], e[N], ne[N];
void insert(int x) {
int k = (x%N+N)%N;
e[idx] = x, ne[idx] = h[k], h[k] = idx++;
}
bool find(int x) {
int k = (x%N+N)%N;
for (int i = h[k]; ~i; i = ne[i]) {
if (e[i] == x) return true;
}
return false;
}
int main() {
memset(h, -1, sizeof h);
cin >> n;
while (n--) {
char op[2];
int x;
cin >> op >> x;
if (*op == 'I') {
insert(x);
} else {
if (find(x)) puts("Yes");
else puts("No");
}
}
return 0;
}
方法:哈希表
class Solution {
public:
bool isAnagram(string s, string t) {
int n = s.size(), m = t.size();
if (n != m) return false;
int a[128], b[128];
memset(a, 0, sizeof a);
memset(b, 0, sizeof b);
for (int i = 0; i < n; ++i) {
++a[s[i]];
++b[t[i]];
}
for (int i = 'a'; i <= 'z'; ++i) if (a[i] != b[i]) return false;
return true;
}
};
$时间复杂度O(n), 空间复杂度O(n);
方法:哈希表
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size();
int a[1001], b[1001];
vector<int> res;
memset(a, 0, sizeof a);
memset(b, 0, sizeof b);
for (int i = 0; i < n; ++i) ++a[nums1[i]];
for (int i = 0; i < m; ++i) ++b[nums2[i]];
for (int i = 0; i < 1001; ++i) if (a[i] && b[i]) res.push_back(i);
return res;
}
};
$时间复杂度O(n), 空间复杂度O(n);
方法:无序集合
class Solution {
private:
int get_val(int n) {
int cur = 0;
while (n) {
int x = n % 10;
cur += x * x;
n /= 10;
}
return cur;
}
public:
bool isHappy(int n) {
unordered_set<int> vis;
while (1) {
int val = get_val(n);
if (val == 1) return true;
if (vis.find(val) != vis.end()) return false;
else vis.insert(val);
n = val;
}
}
};
$时间复杂度O(n), 空间复杂度O(n); n为循环的次数
方法:哈希表
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> vis;
for (int i = 0; i < nums.size(); ++i) {
if (vis.find(target - nums[i]) != vis.end()) return {i, vis[target - nums[i]]};
vis[nums[i]] = i;
}
return {};
}
};
$时间复杂度O(n), 空间复杂度O(n);