#include <iostream> using namespace std; //数组求和 //方法一:时间复杂度为O(n),额外空间为(n) int ArraySum(int arr[],int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += arr[i]; } return sum; } //方法二:递归的方法,时间复杂度为O(n),额外空间为log(n) int ArraySum(int arr[], int low, int high) { if (low == high) return arr[low]; else if (low<high) { int mid = (low + high) >> 1; return ArraySum(arr, low, mid) + ArraySum(arr, mid+1, high); } } int main() { int arr[11] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ,11}; int sum_1, sum_2=0; sum_1 = ArraySum(arr, 11); sum_2 = ArraySum(arr, 0, 11-1); //一定要注意,这里是10而不是11,因为数组下标为准,不存在arr[11],已经溢出 cout << "方法一:" << sum_1 << endl; cout << "方法二:" << sum_2 << endl; return 0; }