Most efficient way to sum up an array of integers

爱⌒轻易说出口 提交于 2021-02-19 03:38:45

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32673076/most-efficient-way-to-sum-up-an-array-of-integers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!