带地图的解决方案给了空调,unordered_map的解决方案给了WA.为什么
Solution with map gave AC and Solution with unordered_map gave WA. why?
我正在寻找现在大多数人都知道的map
和unordere_map
之间的任何区别。
问题 : 问题链接
带地图的解决方案:接受的解决方案
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
map<int,int> mp;
map<int,int> ::iterator it;
int ans = 0;
for(int i=0;i<N;i++){
int X;
cin >> X;
mp[X]++;
}
for(it=mp.begin();it!=mp.end();++it){
int X = it->first;
//cout<<it->first<<" "<<it->second<<endl;
ans = max(ans,mp[(X-1)]+mp[(X)]);
}
cout<<ans<<endl;
return 0;
}
unordered_map
的解决方案:WA解决方案
#include <bits/stdc++.h>
using namespace std;
int main() {
int N;
cin >> N;
unordered_map<int,int> mp;
unordered_map<int,int> ::iterator it;
int ans = 0;
for(int i=0;i<N;i++){
int X;
cin >> X;
mp[X]++;
}
for(it=mp.begin();it!=mp.end();++it){
int X = it->first;
//cout<<it->first<<" "<<it->second<<endl;
ans = max(ans,mp[(X-1)]+mp[(X)]);
}
cout<<ans<<endl;
return 0;
}
Input :
98
7 12 13 19 17 7 3 18 9 18 13 12 3 13 7 9 18 9 18 9 13 18 13 13 18 18 17 17 13 3 12 13 19 17 19 12 18 13 7 3 3 12 7 13 7 3 17 9 13 13 13 12 18 18 9 7 19 17 13 18 19 9 18 18 18 19 17 7 12 3 13 19 12 3 9 17 13 19 12 18 13 18 18 18 17 13 3 18 19 7 12 9 18 3 13 13 9 7
Output : 10
Expected Output : 30
据我所知,与map
和unordered_map
的唯一区别是地图以排序方式包含键,而unordered_map
则不包含。
mp[(X-1)]
可能需要在映射中插入一个新元素(如果键X-1
尚不存在(。使用 std::map
,插入新元素不会使任何现有的迭代器失效。使用 std::unordered_map
,它可能(如果插入碰巧触发重新散列(。当它出现时,it
将变为无效,后续++it
表现出未定义的行为。
相关文章:
- 运行同一解决方案的另一个项目的项目
- Project Euler问题4的错误解决方案
- 计算每个节点的树高,帮助我解释这个代码解决方案
- C++:Application.cpp中抛出了未解析的外部符号(解决方案在问题的末尾,供未来的读者参考)
- visual c++,如何获取解决方案目录中的代码
- 有没有办法在远程设备上打开和编辑visual Studio 2017解决方案
- C++Matching Brackets 2解决方案不起作用
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的固定时间步长与增量时间和插值的解决方案是错误的吗?
- 无法在问题解决方案中执行输出逻辑
- 最大的回文产品 - 程序未运行,编写解决方案但无法理解问题
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- 在一个解决方案中针对第三方静态库 (Creo) 的不同版本(版本)进行构建
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- N-queen问题:无法弄清楚为什么我的解决方案不起作用
- 从排序数组中删除重复项,具有不同代码方式的相同解决方案具有不同的输出
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- std::map是一个好的解决方案吗