题解 | #记票统计#
记票统计
https://www.nowcoder.com/practice/3350d379a5d44054b219de7af6708894
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here let arrinput = []; while ((line = await readline())) { arrinput.push(line); } let people = arrinput[1].split(" "); let vote = arrinput[3].split(" "); // // 方法1:循环查找 // // 定义num统计所有的合法票数 // let num = 0; // // 定义result数组用于存放“人员 : 票数”结果 // let result = []; // people.forEach((item, index) => { // // 定义count用于统计每一个人的合法得票数 // let count = 0; // // 循环统计每一个人共有多少张得票 // vote.forEach((x, i) => { // if (item == x) { // count++; // } // }); // // 每一个人循环结束后,将其票数加到总得合法票数中 // num += count; // // 存放结果 // result.push(item + " " + ":" + " " + count); // }); // // 循环存放人员得票之后,存放不合规的票数 // result.push("Invalid : " + (vote.length - num)); // // 依次输出结果 // for (let item of result) { // console.log(item); // } // 方法2:对象 let obj = {}; let num = +arrinput[2]; let count = 0; // 统计所有票的数量,包括合法和不合法 for (let item of vote) { if (obj[item]) { obj[item]++; } else { obj[item] = 1; } } // 对每一位候选人,输出得票结果 for (let item of people) { // 如果候选人不在obj中,则添加其为0 if (obj[item] == undefined) { obj[item] = 0; } // 统计总的候选人的得票数 count += obj[item]; // 输出结果 console.log(item + " : " + obj[item]); } // 最后输出不合法的票数 console.log("Invalid : " + (num - count)); })();