Skip to content

Commit 5ad75c4

Browse files
committed
Time: 1079 ms (5.50%), Space: 153 MB (30.19%) - LeetHub
1 parent cb4134d commit 5ad75c4

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
class NumArray {
2+
public:
3+
vector<int>A,tree;
4+
int n;
5+
void build(int node, int start, int end)
6+
{
7+
if(start == end)
8+
{
9+
// Leaf node will have a single element
10+
tree[node] = A[start];
11+
}
12+
else
13+
{
14+
int mid = (start + end) / 2;
15+
// Recurse on the left child
16+
build(2*node+1, start, mid);
17+
// Recurse on the right child
18+
build(2*node+2, mid+1, end);
19+
// Internal node will have the sum of both of its children
20+
tree[node] = tree[2*node+2] + tree[2*node+1];
21+
}
22+
}
23+
24+
void update1(int node, int start, int end, int idx, int val)
25+
{
26+
if(start == end)
27+
{
28+
// Leaf node
29+
A[idx] = val;
30+
tree[node] = val;
31+
}
32+
else
33+
{
34+
int mid = (start + end) / 2;
35+
if(start <= idx and idx <= mid)
36+
{
37+
// If idx is in the left child, recurse on the left child
38+
update1(2*node+1, start, mid, idx, val);
39+
}
40+
else
41+
{
42+
// if idx is in the right child, recurse on the right child
43+
update1(2*node+2, mid+1, end, idx, val);
44+
}
45+
// Internal node will have the sum of both of its children
46+
tree[node] = tree[2*node+1] + tree[2*node+2];
47+
}
48+
}
49+
50+
int query1(int node, int start, int end, int l, int r)
51+
{
52+
if(r < start or end < l)
53+
{
54+
// range represented by a node is completely outside the given range
55+
return 0;
56+
}
57+
if(l <= start and end <= r)
58+
{
59+
// range represented by a node is completely inside the given range
60+
return tree[node];
61+
}
62+
// range represented by a node is partially inside and partially outside the given range
63+
int mid = (start + end) / 2;
64+
int p1 = query1(2*node+1, start, mid, l, r);
65+
int p2 = query1(2*node+2, mid+1, end, l, r);
66+
return (p1 + p2);
67+
}
68+
69+
70+
NumArray(vector<int>& nums) {
71+
72+
//tree.resize(100000,0);
73+
n=nums.size();
74+
tree.resize(4*n,0);
75+
A=nums;
76+
build(0,0,n-1);
77+
}
78+
79+
void update(int index, int val) {
80+
81+
return update1(0,0,n-1,index,val);
82+
}
83+
84+
int sumRange(int left, int right) {
85+
86+
return query1(0,0,n-1,left,right);
87+
}
88+
};
89+
90+
/**
91+
* Your NumArray object will be instantiated and called as such:
92+
* NumArray* obj = new NumArray(nums);
93+
* obj->update(index,val);
94+
* int param_2 = obj->sumRange(left,right);
95+
*/

0 commit comments

Comments
 (0)