0%

leetcode Count of Range Sum

leetcode Count of Range Sum

Given an integer array nums, return the number of range sums that lie in [lower, upper] inclusive. Range sum S(i, j) is defined as the sum of the elements in nums between indices i and j (ij), inclusive.

Note: A naive algorithm of O(_n_2) is trivial. You MUST do better than that.

Example: Given nums = [-2, 5, -1], lower = -2, upper = 2, Return 3. The three ranges are : [0, 0], [2, 2], [0, 2] and their respective sums are: -2, -1, 2. 题目地址: leetcode Count of Range Sum

题意:

给定一个整数组成的数组,求它的所有子区间和坐落于[lower, upper] 的个数。

比如样例中[-2, 5, -1]中,这三个区间的和在[-2,2]之间 [0, 0], [2, 2], [0, 2]

思路

先来看看最朴素的O(n^2)算法,首先算出和,然后枚举区间范围。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int countRangeSum(int[] nums, int lower, int upper) {
if(nums.length == 0) return 0;
long[] sum = new long[nums.length + 1];
for (int i = 0; i < nums.length; i++)
sum[i + 1] = sum[i] + nums[i];

int ans = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j <= nums.length; j++) {
if(lower <= sum[j] - sum[i] && sum[j] - sum[i] <= upper)
ans++;
}
}
return ans;
}
}

 

题目要求的效率好于O(n^2)的算法,那么要怎么加速呢?

还记得 Count of Smaller Numbers After Self  么?

那时候,我们用Fenwick树或者线段树,先离散化,然后从右向左扫描,每扫描一个数,对小于它的求和。然后更新.....

这题也差不多,需要找满足条件 lower ≤ sum[j] - sum[i - 1] ≤ upper ,也就是lower + sum[i - 1] ≤ sum[j] ≤ upper + sum[i - 1]

我们同样的求出和,然后离散化,接着从右向左扫描,对每个i 查询满足在[ lower + sum[i - 1], upper + sum[i - 1] ]范围内的个数(用线段树或者Fenwick Tree)

这样复杂度就是O(n log n)

线段树

C++

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
typedef long long LL;
struct SegmentTreeNode {
LL L, R;
int cnt;
SegmentTreeNode *left, *right;
SegmentTreeNode(LL L, LL R) :L(L), R(R), cnt(0), left(NULL), right(NULL) {}
};

class SegmentTree {
SegmentTreeNode * root;
SegmentTreeNode * buildTree(vector<LL> &nums, int L, int R) {
if (L > R) return NULL;
SegmentTreeNode * root = new SegmentTreeNode(nums[L], nums[R]);
if (L == R) return root;
int mid = (L + R) >> 1;
root->left = buildTree(nums, L, mid);
root->right = buildTree(nums, mid + 1, R);
return root;
}

void update(SegmentTreeNode * root, LL val) {
if (root && root->L <= val && val <= root->R) {
root->cnt++;
update(root->left, val);
update(root->right, val);
}
}

int sum(SegmentTreeNode * root, LL L, LL R) {
if (!root || root->R < L || R < root->L ) return 0;
if (L <= root->L && root->R <= R) return root->cnt;
return sum(root->left, L, R) + sum(root->right, L, R);
}

public:
SegmentTree(vector<LL> &nums, int L, int R) { root = buildTree(nums, L, R); }

int sum(LL L, LL R) {
return sum(root, L, R);
}

void update(LL val) {
update(root, val);
}
};

class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
if (nums.size() == 0) return 0;
vector<LL> sum_array (nums.size(),0);
sum_array[0] = nums[0];
for (int i = 1; i < sum_array.size(); i++) {
sum_array[i] = nums[i] + sum_array[i - 1];
}
LL sum = sum_array[sum_array.size() - 1];
sort(sum_array.begin(), sum_array.end());
auto t = unique(sum_array.begin(), sum_array.end());
SegmentTree tree(sum_array, 0, t - sum_array.begin() - 1);
int ans = 0;
for (int i = nums.size() - 1; i >= 0; i--) {
tree.update(sum);
sum -= nums[i];
ans += tree.sum(lower + sum,upper + sum);
}
return ans;
}
};

 

Binary indexed tree (Fenwick tree)

关于此树的介绍: Binary indexed tree (Fenwick tree)

注意要加入upper 和 lower -1 两个点

(python 版本比C++简洁太多了^ ^,建议看py版本)

C++

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
typedef long long LL;
class FenwickTree {
vector<int> sum_array;
int n;
inline int lowbit(int x) {
return x & -x;
}

public:
FenwickTree(int n) :n(n), sum_array(n + 1, 0) {}

void add(int x, int val) {
while (x <= n) {
sum_array[x] += val;
x += lowbit(x);
}
}

int sum(int x) {
int res = 0;
while (x > 0) {
res += sum_array[x];
x -= lowbit(x);
}
return res;
}
};

class Solution {
public:
int countRangeSum(vector<int>& nums, int lower, int upper) {
if (nums.size() == 0) return 0;
vector<LL> sum_array (nums.size() * 3,0);
LL sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
sum_array[i * 3] = sum;
sum_array[i * 3 + 1] = sum + lower - 1;
sum_array[i * 3 + 2] = sum + upper;
}
sum_array.push_back(upper);
sum_array.push_back(lower - 1);
unordered_map<LL, int> index;
sort(sum_array.begin(), sum_array.end());
auto end = unique(sum_array.begin(), sum_array.end());
auto it = sum_array.begin();
for (int i = 1; it != end;i++,it++) {
index[*it] = i;
}
FenwickTree tree(index.size());
int ans = 0;
for (int i = nums.size() - 1; i >= 0; i--) {
tree.add(index[sum],1);
sum -= nums[i];
ans += tree.sum(index[upper + sum]) - tree.sum(index[lower + sum -1]);
}
return ans;
}
};

 

Python

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
class FenwickTree(object):
def __init__(self, n):
self.sum_array = [0] * (n + 1)
self.n = n

def lowbit(self, x):
return x & -x

def add(self, x, val):
while x <= self.n:
self.sum_array[x] += val
x += self.lowbit(x)

def sum(self, x):
res = 0
while x > 0:
res += self.sum_array[x]
x -= self.lowbit(x)
return res

class Solution(object):
def countRangeSum(self, nums, lower, upper):
"""
:type nums: List[int]
:type lower: int
:type upper: int
:rtype: int
"""
if not nums: return 0
sum_array = [upper, lower - 1]
total = 0
for num in nums:
total += num
sum_array += [total, total + lower - 1, total + upper]

index = {}
for i, x in enumerate(sorted(set(sum_array))):
index[x] = i + 1

tree = FenwickTree(len(index))
ans = 0
for i in xrange(len(nums) - 1, -1, -1):
tree.add(index[total], 1)
total -= nums[i]
ans += tree.sum(index[upper + total]) - tree.sum(index[lower + total - 1])
return ans

 

本文是 leectode 327 Count of Range Sum 的题解,

更多leetcode题解见 https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~