我有这个函数,它根据阵列分区的位置P返回数组两部分之和的最小差值。测试编程以在O(N * N)时间复杂度和0%性能下运行,尽管预期O(N)。
问题:我有什么方面可以改变以提高性能吗?有没有更好的方法在不使用子循环的情况下在循环内求和数组?感谢
任何整数P,使得0 <0。 P&lt; N,将此磁带分成两个非空部分: A [0],A [1],...,A [P-1]和A [P],A [P + 1],...,A [N-1]。
两部分之间的差异是: |(A [0] + A [1] + ... + A [P-1]) - (A [P] + A [P + 1] + ... + A [N - 1])|
function solution(A) {
'use strict';
if(arguments.length === 1 && typeof A === "object" && A.length > 1 ){
try{
const N = A.length;
let diff;
for( let P =1 ; P < N ; P++) {
// For each value of P, calc the difference
//|(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
// use slice to prevent modification of oraginal copy
var A2 = A.slice(0) ;
//splice array into two A1 and A2
let A1 = A2.splice(0, P); // All Element from start up to P
console.log("From Array " + A + " Remove "+ A1 + " Remaining " + A2);
// reduce((a, b) => a + b, 0);
let diffp = Math.abs((A1.reduce(function(a, b) { return a + b; }, 0)) -
(A2.reduce(function(a, b) { return a + b; }, 0))) ;
if(diff > diffp || diff === undefined ){
diff = diffp ;
}
console.log(P + "Difference ="+ diff + " Instead of " + diffp + " \r\n " );
}
// Return the Minimum value of P
return diff ;
}
catch(err){
console.log("Error: " + err );
return 0 ; // undefined ;
}
}else{
console.log("Invalid parameter(s)");
return 0 ; // undefined ;
}
}
var A = [] ;
A[0] = 5
A[1] = 1
A[2] = 2
A[3] = 7
A[4] = 4
console.log(solution(A)) ;
答案 0 :(得分:1)
是的,用线性时间(甚至是恒定的空间)和运行总和来做这件事是非常微不足道的。
function solution(arr) {
var leftSum = 0; // sum from 0 to P
var rightSum = arr.reduce((a, b) => a + b, 0); // sum from P to N
var min = Math.abs(leftSum - rightSum); // initial value for p=0
for (var p = 0; p < arr.length; p++)
// move the element from the right to the left side
leftSum += arr[p];
rightSum -= arr[p];
// then update minimum difference
min = Math.min(min, Math.abs(leftSum - rightSum));
}
return min;
}