faster implementation of sum ( for Codility test )

前端 未结 22 2121
鱼传尺愫
鱼传尺愫 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 did the same naive implementation and here's my O(n) solution. I did not use the IEnumerable Sum method because it was not available at Codility. My solution still doesn't check for overflow in case the input has large numbers so it's failing that particular test on Codility.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var list = new[] {-7, 1, 5, 2, -4, 3, 0};
                Console.WriteLine(equi(list));
                Console.ReadLine();
            }
    
            static int equi(int[] A)
            {
                if (A == null || A.Length == 0)
                    return -1;
    
                if (A.Length == 1)
                    return 0;
    
                var upperBoundSum = GetTotal(A);
                var lowerBoundSum = 0;
                for (var i = 0; i < A.Length; i++)
                {
                    lowerBoundSum += (i - 1) >= 0 ? A[i - 1] : 0;
                    upperBoundSum -= A[i];
                    if (lowerBoundSum == upperBoundSum)
                        return i;
                }
                return -1;
            }
    
            private static int GetTotal(int[] ints)
            {
                var sum = 0;
                for(var i=0; i < ints.Length; i++)
                    sum += ints[i];
                return sum;
            }
        }
    }
    

    Codility Results

提交回复
热议问题