如何以大O(N)的时间复杂度对循环中的数组部分求和 [英] How to Sum array parts within a loop with time-complexity of Big O(N)

查看:201
本文介绍了如何以大O(N)的时间复杂度对循环中的数组部分求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此函数,该函数基于数组被分割的位置P返回数组两部分之和之间的最小差。经测试,该程序可以在O(N * N)时间复杂度和0%的性能下运行,尽管预期为O(N)。

I have this function that returns the minimum difference between the sum of two parts of an array based on the position P the Array is partitioned. The programmed is tested to to run at O(N * N) time complexity and 0% performance though O(N) is was expected.

问题:我可以在此方面进行任何改进以改善性能吗?有没有更好的方法可以在不使用子循环的情况下对循环中的数组求和?谢谢

Question: Is there any aspect of this I can change to improve on the performance? Is there a better way to summing array within a loop without using a sub-loop? Thanks

任何整数P,例如0 < P < N,将磁带分割为两个非空部分:
A [0],A [1],...,A [P-1]和A [P],A [P + 1],...。 ..,A [N − 1]。

Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

两个部分之间的差为:
|(A [0] + A [1 ] + ... + A [P-1])-(A [P] + A [P + 1] + ... + A [N-1])|

The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

https://jsbin.com/mehisi/edit

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)) ;


推荐答案

是的,在线性时间内这样做很简单(甚至是恒定空间)。

Yes, it's pretty trivial to do this in linear time (and even constant space) with a running sum.

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;
}

这篇关于如何以大O(N)的时间复杂度对循环中的数组部分求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆