【发布时间】:2020-04-20 11:14:36
【问题描述】:
我有一个这样的数组: [20,40,60,60,20] 要求:将任意两个数字相加,如果结果可被 60 整除,则计数为 1。因此该数组应返回 3 对。 (20,40), (40,20), (60,60)。
这是我编写的代码,但它给了我 4 而不是 3
function countPlayList (array) {
let count = 0;
for (let i = 0; i < array.length-1; i++) {
for (let j = 0; j < array.length-1; j++) {
let a = array[i];
let b = array[j];
if (checkPlayTime(a, b) && notDuplicate(i, j)) {
count++;
}
}
}
return count;
}
function checkPlayTime (a, b) {
return Number.isInteger((a + b)/60);
}
function notDuplicate (x, y) {
return x !== y ? true : false;
}
我这里有什么遗漏吗?
【问题讨论】:
-
为什么
notDuplicate()([30, 30]应该是 1,或者不是)?这可能与您的for循环中的条件有关。您可能需要考虑在每个循环中必须检查哪些元素。 -
您指定的 3 对不正确 - 实际上是 (20, 40)、(40, 20) 和 (40, 20) - 而不是 (60, 60) 会在以下情况下返回 false notDuplicate 被调用。
-
请注意:这可以在平均 O(n) 中完成。模 60,加法逆很清楚,所以只需保持计数:
arr.map(e => e % 60).reduce((p, c) => { p.n += p[(60 - c) % 60] || 0; p[c] = (p[c] || 0) + 1; return p; }, { n: 0 }).n
标签: javascript arrays duplicates nested-loops