#include <map>
using namespace std;
int main() {
map<string, int> m;
// Insert key-value pairs
m["abc"] = 100;
m["def"] = 200;
// Access value using key
int value1 = m["abc"]; // value1 is 100
// Check if key exists
if (m.count("def") > 0) {
// Key exists
}
if (m.find("abc") == m.end())
//key does not exist
// Iterate through map
for (auto& p : m) {
cout << p.first << " -> " << p.second << endl;
}
// Erase key
m.erase("abc");
// Get size
int size = m.size();
}
Other useful functions are:
- .begin() and .end() to get iterators
- .clear() to remove all elements
- .empty() to check if map is empty
Time Complexity:
For map and set(which normally implemented as red-black trees):
Lookup - O(log n)
Insertion - O(log n)
Deletion - O(log n)
Iteration - O(n)
Space Complexity - O(n)
For unordered_map and unordered_set (which usually uses hash tables):
Lookup - O(1) Average Insertion - O(1) Average Deletion - O(1) Average Iteration - O(n)
Space - O(n)
(一) 哈希表
前言: 把哈希表放在前端是因为由于本身搜索Time complexity = O(1)哈希表是leetcode几乎是最常用的一种map.
例题: 242/ 1002/394/202/1* /454/383/15/18
常见用法: map<char, int> a == b; map和vector一样, stl内置 == 功能
Sort
leetcode 刷题错误点: map 和 set虽然是内置已经sorted了。但是重复数值会被覆盖. 在使用其内置sort 属性中,一定要考虑重复数值是否会被覆盖。
vector sort 方法: 注意加上static
static bool compare(pair<int, int> a, pair<int, int> b){
return a.first < b.first;
}//排序顺序为pair的first element ascend
vector<pair<int, int>> a;
sort(a.begin(), a.end(), compare);
例题: 374