Map + Set + unordered_map + unordered_set

文章讨论了C++中的map和unordered_map容器,包括它们的插入、查找、删除操作的时间复杂度。同时提到了哈希表在LeetCode问题中的重要性,并举例说明了常见的错误,如重复数值覆盖及排序问题。此外,还介绍了其他相关操作如迭代和获取容器大小。
摘要由CSDN通过智能技术生成
#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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值