faster implementation of sum ( for Codility test )

前端 未结 22 2140
鱼传尺愫
鱼传尺愫 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:38

    I have scored 100% for this one:

    int equi (int[] A)
    {
        if (A == null) return -1;
    
        long sum0 = 0, sum1 = 0;
    
        for (int i = 0; i < A.Length; i++) sum0 += A[i];
    
        for (int i = 0; i < A.Length; i++)
        {
            sum0 -= A[i];
            if (i > 0)
            {
                sum1 += A[i - 1];
            }          
            if (sum1 == sum0) return i;      
        }        
        return -1;
    }
    

提交回复
热议问题