题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int nTest;
cin >> nTest;
vector<vector<int>> vecTest(nTest, vector<int> (2, 0));
for(int i = 0; i < nTest; i++){
cin >> vecTest[i][0] >> vecTest[i][1];
}
// 按列元素排序
sort(vecTest.begin(), vecTest.end());
// 合并相同的元素,注意要遍历到倒数第二个元素!!!!!!!
//注意:vecTest.size()返回的是列数;
//vecTest.erase(vecTest.begin() + i + 1)删除的是对应的行
int i = 0;
while(i < vecTest.size() - 1){
if(vecTest[i][0] == vecTest[i+1][0]){
vecTest[i][1] += vecTest[i+1][1];
vecTest.erase(vecTest.begin() + i + 1);
}else{
i++;
}
}
// 输出vector矩阵
for (const auto& row : vecTest) {
for (int value : row) {
cout << value << " ";
}
cout << endl;
}
}
查看24道真题和解析