【发布时间】:2018-09-16 18:18:24
【问题描述】:
我试图让我的函数返回数组索引的最大数量,当按顺序相加时,等于 0 - 不容易解释,但下面是一些带注释的测试示例:
longestSlice([-1, -1, 1, -1, 1, 0, 1, -1, -1]); // should return 7 (slice starts at 2nd position)
longestSlice([1, 1, -1, -1, -1, -1, -1, 1, 1]); // should return 4 (both the first four elements and the last four elements)
longestSlice([-1, -1, -1, -1, 1, 0, 1, -1, -1]); // should return 5 (slice starts at 4th position)
我的函数正确返回前 2 个测试,但不是第 3 个测试。我认为我的逻辑是错误的,但我一生都无法弄清楚解决它的逻辑。如何实现?我试过了:
// if a[i] + a[i+1] = 0, count++, then if a[i-1] + a[i+2] = 0, count++ etc - won't work
// if a[i] + a[i+1] + a[i+2] + ... + a[i+n/2] > n (or -n) - won't work
// tests considering: count no of -1, 0 and 1 instances
另外,有人可以解释一下如何轻松解决这种情况,因为它看起来比看起来更困难,而且我对 javascript 还比较陌生。感谢您在这里的任何建议。
function longestSlice(arr) {
var N = arr.length;
var totalSum = 0, sliceLength = 0;
var slices = [];
if (N < 1) {
throw new RangeError('Bad Input - Function Aborted');
} else {
// continue...
for (i = 0; i < N; i++) {
totalSum += arr[i];
sliceLength++;
console.log('totalSum: ' + totalSum + '\nsliceLength: ' + sliceLength);
if (totalSum === 0) {
slices.push(sliceLength);
sliceLength = 0;
console.log('sliceLength reset to: ' + sliceLength);
}
}
return slices;
}
}
【问题讨论】:
标签: javascript algorithm