forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
count-of-range-sum.cpp
86 lines (80 loc) · 3.08 KB
/
count-of-range-sum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Time: O(nlogn)
// Space: O(n)
// Divide and Conquer solution.
class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
vector<long long> sums(nums.size() + 1);
for (int i = 0; i < nums.size(); ++i) {
sums[i + 1] = sums[i] + nums[i];
}
return countAndMergeSort(&sums, 0, sums.size(), lower, upper);
}
int countAndMergeSort(vector<long long> *sums, int start, int end, int lower, int upper) {
if (end - start <= 1) { // The number of range [start, end) of which size is less than 2 is always 0.
return 0;
}
int mid = start + (end - start) / 2;
int count = countAndMergeSort(sums, start, mid, lower, upper) +
countAndMergeSort(sums, mid, end, lower, upper);
int j = mid, k = mid, r = mid;
vector<long long> tmp;
for (int i = start; i < mid; ++i) {
// Count the number of range sums that lie in [lower, upper].
while (k < end && (*sums)[k] - (*sums)[i] < lower) {
++k;
}
while (j < end && (*sums)[j] - (*sums)[i] <= upper) {
++j;
}
count += j - k;
// Merge the two sorted arrays into tmp.
while (r < end && (*sums)[r] < (*sums)[i]) {
tmp.emplace_back((*sums)[r++]);
}
tmp.emplace_back((*sums)[i]);
}
// Copy tmp back to sums.
copy(tmp.begin(), tmp.end(), sums->begin() + start);
return count;
}
};
// Divide and Conquer solution.
class Solution2 {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
vector<long long> sums(nums.size() + 1);
for (int i = 0; i < nums.size(); ++i) {
sums[i + 1] = sums[i] + nums[i];
}
return countAndMergeSort(&sums, 0, sums.size() - 1, lower, upper);
}
int countAndMergeSort(vector<long long> *sums, int start, int end, int lower, int upper) {
if (end - start <= 0) { // The number of range [start, end] of which size is less than 2 is always 0.
return 0;
}
int mid = start + (end - start) / 2;
int count = countAndMergeSort(sums, start, mid, lower, upper) +
countAndMergeSort(sums, mid + 1, end, lower, upper);
int j = mid + 1, k = mid + 1, r = mid + 1;
vector<long long> tmp;
for (int i = start; i <= mid; ++i) {
// Count the number of range sums that lie in [lower, upper].
while (k <= end && (*sums)[k] - (*sums)[i] < lower) {
++k;
}
while (j <= end && (*sums)[j] - (*sums)[i] <= upper) {
++j;
}
count += j - k;
// Merge the two sorted arrays into tmp.
while (r <= end && (*sums)[r] < (*sums)[i]) {
tmp.emplace_back((*sums)[r++]);
}
tmp.emplace_back((*sums)[i]);
}
// Copy tmp back to sums.
copy(tmp.begin(), tmp.end(), sums->begin() + start);
return count;
}
};