faster implementation of sum ( for Codility test )

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

    I don't think your problem is with the function that's summing the array, it's probably that you're summing the array WAY to frequently. If you simply sum the WHOLE array once, and then step through the array until you find the first equilibrium point you should decrease the execution time sufficiently.

    int equi ( int[] A ) {
        int equi = -1;
    
        long lower = 0;
        long upper = 0;
        foreach (int i in A)
            upper += i;
    
        for (int i = 0; i < A.Length; i++)
        {
            upper -= A[i];
            if (upper == lower)
            {
                equi = i;
                break;
            }
            else
                lower += A[i];
        }
    
        return equi;
    }
    

提交回复
热议问题