@@ -42,3 +42,45 @@ class Solution {
42
42
return count;
43
43
}
44
44
};
45
+
46
+ // Divide and Conquer solution.
47
+ class Solution2 {
48
+ public:
49
+ int countRangeSum (vector<int >& nums, int lower, int upper) {
50
+ vector<long long > sums (nums.size () + 1 );
51
+ for (int i = 0 ; i < nums.size (); ++i) {
52
+ sums[i + 1 ] = sums[i] + nums[i];
53
+ }
54
+ return countAndMergeSort (&sums, 0 , sums.size () - 1 , lower, upper);
55
+ }
56
+
57
+ int countAndMergeSort (vector<long long > *sums, int start, int end, int lower, int upper) {
58
+ if (end - start <= 0 ) { // The number of range [start, end] of which size is less than 2 is always 0.
59
+ return 0 ;
60
+ }
61
+ int mid = start + (end - start) / 2 ;
62
+ int count = countAndMergeSort (sums, start, mid, lower, upper) +
63
+ countAndMergeSort (sums, mid + 1 , end, lower, upper);
64
+ int j = mid + 1 , k = mid + 1 , r = mid + 1 ;
65
+ vector<long long > tmp;
66
+ for (int i = start; i <= mid; ++i) {
67
+ // Count the number of range sums that lie in [lower, upper].
68
+ while (k <= end && (*sums)[k] - (*sums)[i] < lower) {
69
+ ++k;
70
+ }
71
+ while (j <= end && (*sums)[j] - (*sums)[i] <= upper) {
72
+ ++j;
73
+ }
74
+ count += j - k;
75
+
76
+ // Merge the two sorted arrays into tmp.
77
+ while (r <= end && (*sums)[r] < (*sums)[i]) {
78
+ tmp.emplace_back ((*sums)[r++]);
79
+ }
80
+ tmp.emplace_back ((*sums)[i]);
81
+ }
82
+ // Copy tmp back to sums.
83
+ copy (tmp.begin (), tmp.end (), sums->begin () + start);
84
+ return count;
85
+ }
86
+ };
0 commit comments