哈希表的理论基础
- 常见的三种哈希结构
-
数组
-
set集合
-
-
std::set 红黑树 有序 元素不能重复 不能更改数值 查询效率O(logN) 增删效率O(logN)
-
std::multiset 红黑树 有序 元素可以重复 不能更改数值 查询效率O(logN) 增删效率O(logN)
-
std::unordered_set 哈希表 无序 元素不能重复 不能更改数值 查询效率O(1) 增删效率O(1)
- map映射
-
std::map 红黑树 key有序 key不可重复 key不可修改 查询效率O(logN) 增删效率O(logN)
-
std::multimap 红黑树 key有序 key可重复 key不可修改 查询效率O(logN) 增删效率O(logN)
-
std::unordered_map 红黑树 key无序 key不可重复 key不可修改 查询效率O(1) 增删效率O(1)
using namespace std;
set<int> s;
set<int>::iterator it;
multiset<int> sm;
multiset<int>::iterator itm;
unordered_set<int> uoset;
unordered_map<int,int> uomap;
unordered_map<int,int>::iterator uomap_it;
s.insert(1);
s.insert(2);
uomap.insert(pair<int,int>(1,2));
for(it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
}
it = s.find(2);
//check whether find out
if(it != s.end())
// find map's key, not value
uomap_it = uomap.find(1);
// check map's value
uomap_it->second;
uomap[1];
# 列表初始化
set<int> s={1,2,4,5};
# 赋值初始化
set<int> s1=s;
# 拷贝初始化
set<int> s2(s1);
# 范围初始化
set<int> s3(s2.begin(), s2.end());
1.3 map映射
有效的字母异位词-242
Given two strings `s` and `t`, return `true` *if* `t` *is an anagram of* `s` *, and* `false` *otherwise*.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
要点:
- String 类型使用
string t;
string的遍历: for(int i = 0; i < t.size(); i ++)
错误:
- 没有考虑到负数的情况
两个数组的交集-349
Given two integer arrays `nums1` and `nums2`, return *an array of their intersection*. Each element in the result must be **unique** and you may return the result in **any order**.
要点:
- 理解STL容器底层逻辑
错误:
- 容器使用范围初始化
两数之和-1
Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*.
You may assume that each input would have ***exactly* one solution**, and you may not use the *same* element twice.
You can return the answer in any order.
要点:
- 了解map容器的使用
错误:
- 如何返回一个空容器
- 查找元素时不能包括自身
四数相加-454
Given four integer arrays `nums1`, `nums2`, `nums3`, and `nums4` all of length `n`, return the number of tuples `(i, j, k, l)` such that:
- `0 <= i, j, k, l < n`
- `nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0`
要点:
- 二分法 + hashmap
错误:
思考题:一个数组找出四个元素
三数之和-15
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
Notice that the solution set must not contain duplicate triplets.
要点:
- 如何使用容器排序
错误:
- 标定元素去重
思考题:
- 两数之和能否用双指针法? 回答:不行,其需要返回原始下标值,意味着顺序不能更改,不能使用sort函数。
四数之和-18
Given an array `nums` of `n` integers, return *an array of all the **unique** quadruplets* `[nums[a], nums[b], nums[c], nums[d]]` such that:
- `0 <= a, b, c, d < n`
- `a`, `b`, `c`, and `d` are **distinct**.
- `nums[a] + nums[b] + nums[c] + nums[d] == target`
You may return the answer in **any order**.
要点:
- 双指针法
错误:
-
考虑overflow
-
双重循环去重