简体   繁体   中英

Most efficient way to sum up an array of integers

I am trying to find a sub- O(n) method to calculate the sum of an integer array ~~~(instead of iterating through 0 - n , I am doing it in n/2 )~~~ I'm still doing it in O(n) .

public static int sum(int[] s) {
    int length = s.length - 1;
    int half = length/2;
    int sum = 0;
    for(int i = 0; i <= half; i++) {
        System.out.println(i + " " + s[i] + " + " + s[length - i]);
        sum += s[i] + s[length - i];
    }
    return sum;
}

My algorithm works for even number of integers, however, when there are odd number of integers, it would sum the middle index twice:

Test:

    int[] arr = {1, 2, 3, 4, 5};
    System.out.println(sum(arr));

Output:

0 1 + 5
1 2 + 4
2 3 + 3
Sum: 18

My question is - what is the best way to sum up the middle index for odd-number of numbers?

That's still O(n) even if you go from 0 to n/2 at the end of the day you are touching every element of the array at least one time. And to sum up an array of integers the least you can do is O(n) because you have to touch every element in the array one time to include it in the sum.

You solution is O(n), not sub-O(n). Just by adding two numbers inside the loop does not change it. There is no way to make it sub-O(n), as you need to iterate over all numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM