faster implementation of sum ( for Codility test )

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

    Here is my answer with with explanations on how to go about it. It will get you 100%

    class Solution
    {
        public int solution(int[] A)
        {
            long sumLeft = 0;       //Variable to hold sum of elements to the left of the current index
            long sumRight = 0;      //Variable to hold sum of elements to the right of the current index
            long sum = 0;           //Variable to hold sum of all elements in the array
            long leftHolder = 0;    //Variable that holds the sum of all elements to the left of the current index, including the element accessed by the current index
    
            //Calculate the total sum of all elements in the array and store it in the sum variable
            for (int i = 0; i < A.Length; i++)
            {
                //sum = A.Sum();
                sum += A[i];
            }
            for (int i = 0; i < A.Length; i++)
            {
                //Calculate the sum of all elements before the current element plus the current element
                leftHolder += A[i];
                //Get the sum of all elements to the right of the current element
                sumRight = sum - leftHolder;
                //Get the sum of all elements of elements to the left of the current element.We don't include the current element in this sum
                sumLeft = sum - sumRight - A[i];
                //if the sum of the left elements is equal to the sum of the right elements. Return the index of the current element
                if (sumLeft == sumRight)
                    return i;
            }
            //Otherwise return -1
            return -1;
        }
    }
    

提交回复
热议问题