题解 | #合并表记录#
合并表记录
https://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
#include <stdio.h>
int main() {
typedef struct {
int key;
int value;
} MapObject;
MapObject mapObject[1000];
int total;
scanf("%d", &total);
for (int i = 0; i < total; i++) {
int key, value;
scanf("%d %d", &key, &value);
mapObject[i].key = key;
mapObject[i].value = value;
}
for (int i = 0; i < total - 1; i++) {
for (int j = 0; j < total - 1 - i; j++) {
if (mapObject[j].key > mapObject[j + 1].key) {
MapObject temp = mapObject[j];
mapObject[j] = mapObject[j + 1];
mapObject[j + 1] = temp;
}
}
}
for (int i = 0; i < total; i++) {
if (mapObject[i + 1].key == mapObject[i].key) {
mapObject[i + 1].value += mapObject[i].value;
mapObject[i].value = 0;
}
if (mapObject[i].value) printf("%d %d\n", mapObject[i].key, mapObject[i].value);
}
return 0;
}

查看8道真题和解析