faster implementation of sum ( for Codility test )

前端 未结 22 2096
鱼传尺愫
鱼传尺愫 2021-02-04 11:47

How can the following simple implementation of sum be faster?

private long sum( int [] a, int begin, int end ) {
    if( a == null   ) {
        ret         


        
22条回答
  •  逝去的感伤
    2021-02-04 12:25

    This got me 100% in Javascript:

    function solution(A) {
        if (!(A) || !(Array.isArray(A)) || A.length < 1) {
            return -1;
        }
    
        if (A.length === 1) {
            return 0;
        }
    
        var sum = A.reduce(function (a, b) { return a + b; }),
            lower = 0,
            i,
            val;
    
        for (i = 0; i < A.length; i++) {
            val = A[i];
            if (((sum - lower) - val) === (lower)) {
                return i;
            }
            lower += val;
        }
    
        return -1;
    }
    

    Equilibrium test results screenshot (Javascript)

提交回复
热议问题