faster implementation of sum ( for Codility test )

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

    In C++, the following:

    int* a1 = a + begin;
    for( int i = end - begin - 1; i >= 0 ; i-- )
    {
        r+= a1[i];
    }
    

    might be faster. The advantage is that we compare against zero in the loop.

    Of course, with a really good optimizer there should be no difference at all.

    Another possibility would be

    int* a2 = a + end - 1;
    for( int i = -(end - begin - 1); i <= 0 ; i++ )
    {
        r+= a2[i];
    }
    

    here we traversing the items in the same order, just not comparing to end.

提交回复
热议问题