c++ - C++ unordered_map 奇怪的行为
问题描述
我正在解决 leetcode 问题(总持续时间可被 60 整除的歌曲对),下面的解决方案使用地图,当我将其更改为 unordered_map 并打印循环内的元素时;元素的数量远远多于输入
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
//cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << 60 - f << "\n";
ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};
样本输入测试:[15、63、451、213、37、209、343、319]
输出如下:
3 57
15 45
19 41
29 31
31 29
33 27
37 23
41 19
43 17
45 15
57 3
循环内打印的元素数量应该只有 8 个,但是使用 unordered_map,元素数量要多得多。
运行不佳的代码如下:
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
unordered_map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
//cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << 60 - f << "\n";
ans += mod_d[(60 - f) % 60] * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};
唯一的区别是使用 ofunordered_map
而不是 amap
它错误地将元素打印为:
19 41
43 17
37 23
33 27
31 29
29 31
3 57
41 19
15 45
41 19
3 57
29 31
31 29
57 3
33 27
37 23
43 17
17 43
19 41
23 37
27 33
任何人都知道为什么会发生这种奇怪的行为?
解决方案
好的,我现在明白了,非常感谢大家的帮助。根据显示访问地图的不同方式的此链接,我看到[]
如果元素不在地图中,则使用运算符会创建元素,这是我的错误。当我应该使用 std::map::at 来检索地图元素时
使固定
首先检查元素是否存在并at()
用于访问它
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
unordered_map<int, int> mod_d;
for(auto el : time) {
if(mod_d.count(el % 60) == 0) {
mod_d[el % 60] = 1;
}else mod_d[el % 60]++;
}
int ans = 0, i = 1;
cout << "Size: " << mod_d.size() << "\n";
for(auto el : mod_d) {
int f = el.first, s = el.second;
cout << f << " " << i++ << "\n";
if(mod_d.count((60 - f) % 60) > 0) ans += mod_d.at((60 - f) % 60) * (((60 - f) % 60) == f ? s - 1 : s);
}
return ans / 2;
}
};
推荐阅读
- java - 递归自定义 Gson 反序列化器
- python-3.x - 使用 regex-python 验证密码
- swift - 使用 SoundAnalysis 框架分析流式音频的延迟时间是多少?
- arm - 为什么此链接描述文件会产生非一地址?
- python-3.x - 如何使用 Python 的 dns 解析器捕获 SERVFAIL 异常?
- pine-script - 非常简单的 Pine 脚本错误:无法调用策略参数
- php - 通过链接而不是集成的弹出窗口使用 PayPal 登录
- php - 具有多个帐户/电子邮件地址的 Gmail API
- scala - Spark 数据集写入镶木地板文件需要很长时间
- javascript - 为什么 JavaScript 的 fetch() 不需要检查状态码 304?