Title Description: For array A of length n, the sub-array of the Subarray and close to 0, requires time complexity O (NLOGN).
1#include <iostream>2#include <algorithm>3#include <math.h>4 5 using namespacestd; 6 7 intFindminsubarry (Const intA[],intN)8 { 9 int*sum =New int[n];Ten //The first n items of array A and, coexist in the sum array Onesum[0] = a[0]; A for(inti =1; I < n; ++i) - { -Sum[i] = sum[i-1] +A[i]; the } - intMin1 = Fabs (sum[0]); - //The minimum of the absolute value of the first n items of the array a min1 - for(inti =1; I < n; ++i) + { - if(Fabs (Sum[i]) <min1) + { AMin1 =fabs (Sum[i]); at } - } -Sort (sum, sum +N); - //find the minimum value of the difference between the adjacent elements of the sum array min2 - intMin2 = Fabs (sum[0]-sum[1]); - for(inti =2; I < n; ++i) in { - if(Fabs (Sum[i]-sum[i-1]) <min2) to { +Min2 = Fabs (Sum[i]-sum[i-1]); - } the }
delete [] sum; * return(Min1 > Min2?)min2:min1); $ } Panax Notoginseng - intMainintargcConst Char*argv[]) the { + inta[Ten] = { to, - A, -, -, - -, -, the, - the, - at, -}; A inta2[5] = {-5,2,2,3,2}; the intmin = Findminsubarry (A,Ten); + intmin2 = Findminsubarry (A2,5); -cout << min <<Endl; $cout << min2 <<Endl; $ return 0; -}
Results
The calculation of the sum itself and the calculation of the adjacent element difference are all O (N), the sort of sum is O (NLOGN), and therefore the total time complexity: O (Nlogn).
0 sub-arrays