faster implementation of sum ( for Codility test )

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

    Here is a thought:

    private static ArrayList equi(int[] A)
    {
        ArrayList answer = new ArrayList();
    
        //if(A == null) return -1; 
        if ((answer.Count == null))
        {
            answer.Add(-1);
            return answer;
        }
    
        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) answer.Add(i);
        //return i;
        }
        //return -1;
        return answer;
    }
    

提交回复
热议问题