牛客网_华为机试_008_合并表记录
来源:互联网 发布:java字符数组赋值 编辑:程序博客网 时间:2024/05/16 02:01
题目描述
数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。
输入描述:
先输入键值对的个数然后输入成对的index和value值,以空格隔开
输出描述:
输出合并后的键值对(多行)
示例1
输入
40 10 21 23 4
输出
0 31 23 4
问题地址:https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201?tpId=37&tqId=21231&tPage=1&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking
思路一:用数组或者vector实现,要求实现初始化一个足够大的vector<int>, 3ms运行时间
#include <iostream>#include <vector>using namespace std;int main(){ int N = 0;while (cin >> N){vector<int> array(10000, -1);for (int i = 0; i < N; i++){int index, num;cin >> index >> num;if (array[index] == -1) //如果未被记录array[index] = 0;array[index] += num;}for (int i = 0; i < 10000; i++){if (array[i] != -1)cout << i << " " << array[i] << endl;}} return 0;}
思路二:利用map的特性实现,简洁明了. 2ms运行时间
#include <iostream>#include <map>using namespace std;int main(){ int N = 0;while (cin >> N){map<size_t, int> myMap;int key, value;while (N-- && cin >> key >> value){myMap[key] += value; //不存在时默认为0, 累加}for (auto it = myMap.cbegin(); it != myMap.cend(); ++it){cout << it->first << " " << it->second << endl;}} return 0;}
阅读全文
0 0
- 牛客网_华为机试_008_合并表记录
- 华为机试 合并表记录
- java----------华为机试------------合并表记录
- 华为机试——合并表记录
- Java - 华为机试训练 - 合并表记录
- 《华为机试在线训练》之合并表记录
- 华为机试——合并表记录
- 牛客网华为在线训练---合并表记录
- 合并表记录(华为机试题)
- 华为机试题:合并表记录
- 华为机试在线训练-牛客网(5)合并表记录
- 华为OJ_1956_合并表记录
- 【华为OJ8】合并表记录
- 华为OJ:合并表记录
- 【华为OJ】合并表记录
- 合并表记录之机试
- 华为OJ(合并表记录)
- 华为OJ(合并表记录)
- java关于多线程的面试题(三道)--参考答案
- JAVA启动参数大全之三:非Stable参数
- Android手机隐藏代码(手机指令大全)
- ado连接池遇到的问题
- Android 积累
- 牛客网_华为机试_008_合并表记录
- Android UI组件
- eventbus3.0使用
- ELK日志
- android样式和主题(style&theme)
- web项目java后台将html表格导出为word表格文件
- tolua++使用示例
- 子网内主机数、子网数、主机总数计算方式
- Activity、Bundle、请求码与结果码、Intent、广播、服务 (一)