零、原题链接
一、题目描述
二、测试用例
三、解题思路
- 基本思路:
建立映射关系map
,相同key
的元素,值进行累加,最后遍历map
输出即可; - 具体思路:
- 遍历所有元素,判断
map
中是否存在该key
:- 不存在,则插入键值对
- 存在,则值相加;
- 遍历
map
,输出键值对。【map 底层是红黑树实现,使用迭代器进行遍历时,默认是从小到大】
- 遍历所有元素,判断
四、参考代码
时间复杂度:
O
(
n
l
o
g
n
)
\Omicron(nlog\;n)
O(nlogn)【map
的查找和插入的复杂度是
O
(
l
o
g
n
)
\Omicron(log\; n)
O(logn)】
空间复杂度:
O
(
n
)
\Omicron(n)
O(n)
#include <iostream>
#include <map>
using namespace std;
int main() {
map<int, int> m;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
if (m.count(x) == 0) {
m.emplace(x, y);
} else {
m[x] += y;
}
}
for (const auto& [key, value] : m) {
cout << key << ' ' << value << endl;
}
}
// 64 位输出请用 printf("%lld")