题解 | #合并表记录#
合并表记录
http://www.nowcoder.com/practice/de044e89123f4a7482bd2b214a685201
使用Map来进行存储key值唯一 然后通过sort来拍下输出
const readline = require("readline");
const r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const lines = [];
r.on("line", function (line) {
lines.push(line);
if (lines.length - 1 === parseInt(lines[0])) {
lines.shift();
const t = new Map();
lines.forEach((item) => {
const [index, value] = item.split(" ");
const exitValue = t.get(index);
if (exitValue) {
t.set(index, exitValue + parseInt(value));
} else {
t.set(index, parseInt(value));
}
});
const b = Array.from(t).sort((a, b)=> {
return parseInt(a[0]) - parseInt(b[0])
})
b.forEach((item) => {
console.log(item[0] + ' ' + item[1]);
});
}
});
Object版本 通过获取key值然后key值相同叠加,通过index排序输出
const readline = require("readline");
const r = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const lines = [];
r.on("line", function (line) {
lines.push(line);
if (lines.length - 1 === parseInt(lines[0])) {
lines.shift();
const t = {};
lines.forEach((item) => {
const [index, value] = item.split(" ");
const exitValue = t[index];
if (exitValue) {
t[index] = exitValue + parseInt(value);
} else {
t[index] = parseInt(value);
}
});
const c = Object.keys(t).sort((a, b) => {
return parseInt(a) - parseInt(b);
});
c.forEach((item) => {
console.log(item + " " + t[item]);
});
}
});