文章目录
哈希表
1.使用场景
遍历数组时,前面遍历的内容需要存储下来,之后查询时需要用常数时间完成。只有用哈希表才不会超时。
2.模板
可以用C++ STL中的模板,unordered_set,unordered_map<T1, T2>,如果key值是int或者char(有限个,只有字母),可以用自己手写的int数组优化时间和空间。
3.LeetCode例题
1)1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
for (int i = 0; i < nums.size(); i ++ )
{
auto it = hash.find(target - nums[i]);
if (it != hash.end())
{
return {it->second, i};
}
hash[nums[i]] = i;
}
return {};
}
};
2)387. 字符串中的第一个唯一字符
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
(key值为字符)
class Solution {
public:
int firstUniqChar(string s) {
int hash[30];
memset(hash,0,sizeof(hash));
for (int i = 0; i < s.length(); i++) {
hash[s[i] - 'a']++;
}
for (int i = 0; i < s.length(); i++) {
if(hash[s[i] - 'a'] == 1) return i;
}
return -1;
}
};
3)AcWing799. 最长连续不重复子序列
#include <iostream>
using namespace std;
const int N = 100010;
int a[N], s[N];
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int res = 0;
for (int i = 0, j = 0; i < n; i++) {
s[a[i]]++;
while (j < i && s[a[i]] > 1) {
s[a[j]]--;
j++;
}
res = max(res, i - j + 1);
}
cout << res;
return 0;
}
4)3. 无重复字符的最长子串
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> hash;
int res = 0;
for (int i = 0, j = 0; i < s.size(); i++) {
hash[s[i]]++;
while (hash[s[i]] > 1) {
hash[s[j]]--;
j++;
}
res = max(res, i - j + 1);
}
return res;
}
};
5) 138. 复制带随机指针的链表
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
unordered_map<Node*, Node*> hash;
Node* copyRandomList(Node* head) {
if (head == NULL) {
return NULL;
}
if (!hash.count(head)) {
auto newhead = new Node(head->val);
hash[head] = newhead;
newhead->next = copyRandomList(head->next);
newhead->random = copyRandomList(head->random);
}
return hash[head];
}
};