Given an integer array nums , return the number of range sums this lie in [lower, upper] inclusive.
Range sum S(i, j) nums i j is defined i as the sum of the elements in between indices and (≤ j ), inclusive.
Note:
A naive algorithm of O(n2) is trivial. You must does better than that.
Example:
Given nums = [-2, 5, -1] , lower = -2 , upper = 2 ,
Return 3 .
The three ranges is: [0, 0] , [2, 2] , and [0, 2] their respective sums are: -2, -1, 2 .
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Solution One:
classSolution { Public: intCountrangesum (vector<int>& Nums,intLowerintUpper) { intres =0; Long Longsum =0; Multiset<Long Long>sums; Sums.insert (0); for(inti =0; I < nums.size (); ++i) {sum+=Nums[i]; Res+ = Distance (Sums.lower_bound (sum-upper), Sums.upper_bound (Sum-lower)); Sums.insert (sum); } returnRes; } };
Solution Two:
classSolution { Public: intCountrangesum (vector<int>& Nums,intLowerintUpper) {Vector<Long> Sums (nums.size () +1,0); for(inti =0; I < nums.size (); ++i) {sums[i+1] = Sums[i] +Nums[i]; } returnCountandmergesort (Sums,0, Sums.size (), lower, upper); } intCountandmergesort (vector<Long> &sums,intStartintEndintLowerintUpper) { if(End-start <=1)return 0; intMID = start + (End-start)/2; intCNT = Countandmergesort (sums, start, mid, lower, upper) +Countandmergesort (sums, mid, end, lower, upper); intJ = Mid, k = Mid, t =mid; Vector<int> Cache (End-start,0); for(inti = start, R =0; I < mid; ++i, + +r) { while(k < end && Sums[k]-sums[i] < lower) + +K; while(J < End && Sums[j]-sums[i] <= Upper) + +J; while(T < end && Sums[t] < sums[i]) cache[r++] = sums[t++]; CACHE[R]=Sums[i]; CNT+ = J-K; } copy (Cache.begin (), Cache.begin ()+ T-start, Sums.begin () +start); returnCNT; }};
Resources:
Https://leetcode.com/discuss/79083/share-my-solution
Https://leetcode.com/discuss/79632/multiset-solution-100ms-binary-search-tree-180ms-mergesort
Https://leetcode.com/discuss/79907/summary-divide-conquer-based-binary-indexed-based-solutions
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Count of range Sum interval and count