题解 | #数组分组#
数组分组
https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
参考其他网友的解答 解答精髓在最后一个function的输入设置中 完整代码如下
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); //前面这些都中规中矩,正常将输入的数组分成三个数组,一个是3的倍数(但不是5的倍数)arr1, 一个是5的倍数(但可以是3的倍数)arr2,剩余的为一组arr3; let lines = []; rl.on("line", function (line) { lines.push(line); if (lines.length > 1) { let arr = lines[1].split(' ').map(Number); let arr1 = arr.filter((v)=>{ return v%3==0 && v%5!=0; }); let arr2 = arr.filter((v)=>{ return v%5==0; }) let arr3 = arr.filter((v)=>{ return v%5!=0 &&v%3!=0; }) let sum1 = arr1.reduce((pre,cur)=>{ return pre+cur; },0); let sum2 = arr2.reduce((pre,cur)=>{ return pre+cur; },0); console.log(isExists(sum1, sum2, arr3, 0)); } }); //最最精彩的是function isExists()内"||"的运用,很巧妙 function isExists(sum1,sum2,nums,index){ if(index == nums.length && sum1 == sum2) return true; if(index < nums.length) return isExists(sum1+parseInt(nums[index]), sum2, nums, index+1) || isExists(sum1, sum2+parseInt(nums[index]), nums, index+1); return false; }