-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
59 lines (54 loc) · 1.38 KB
/
Solution.java
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
class Solution {
public int countRangeSum(int[] nums, int lower, int upper) {
int n = nums.length;
long[] preSum = new long[n + 1];
for (int i = 0; i < n; ++i) {
preSum[i + 1] = preSum[i] + nums[i];
}
TreeSet<Long> ts = new TreeSet<>();
for (long s : preSum) {
ts.add(s);
ts.add(s - upper);
ts.add(s - lower);
}
Map<Long, Integer> m = new HashMap<>();
int idx = 1;
for (long s : ts) {
m.put(s, idx++);
}
int ans = 0;
BinaryIndexedTree tree = new BinaryIndexedTree(m.size());
for (long s : preSum) {
int i = m.get(s - upper);
int j = m.get(s - lower);
ans += tree.query(j) - tree.query(i - 1);
tree.update(m.get(s), 1);
}
return ans;
}
}
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}