Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb7d8556

Browse files
authored
Improved task 307
1 parent639871f commitb7d8556

File tree

1 file changed

+33
-24
lines changed
  • src/main/java/g0301_0400/s0307_range_sum_query_mutable

1 file changed

+33
-24
lines changed
Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,52 @@
11
packageg0301_0400.s0307_range_sum_query_mutable;
22

33
// #Medium #Array #Design #Segment_Tree #Binary_Indexed_Tree
4-
// #2022_07_07_Time_99_ms_(88.96%)_Space_138.9_MB_(5.17%)
4+
// #2023_03_31_Time_92_ms_(90.27%)_Space_75.3_MB_(16.68%)
55

66
publicclassNumArray {
7+
privateint[]tree;
78
privateint[]nums;
8-
privateintsum;
99

1010
publicNumArray(int[]nums) {
11+
tree =newint[nums.length +1];
1112
this.nums =nums;
12-
sum =0;
13-
for (intnum :nums) {
14-
sum +=num;
13+
// copy the array into the tree
14+
System.arraycopy(nums,0,tree,1,nums.length);
15+
for (inti =1;i <tree.length;i++) {
16+
intparent =i + (i & -i);
17+
if (parent <tree.length) {
18+
tree[parent] +=tree[i];
19+
}
1520
}
1621
}
1722

1823
publicvoidupdate(intindex,intval) {
19-
sum -=nums[index] -val;
24+
intcurrValue=nums[index];
2025
nums[index] =val;
26+
index++;
27+
while (index <tree.length) {
28+
tree[index] =tree[index] -currValue +val;
29+
index =index + (index & -index);
30+
}
2131
}
2232

23-
publicintsumRange(intleft,intright) {
24-
intsumRange =0;
25-
if ((right -left) <nums.length /2) {
26-
// Array to sum is less than half
27-
for (inti =left;i <=right;i++) {
28-
sumRange +=nums[i];
29-
}
30-
}else {
31-
// Array to sum is more than half
32-
// Better to take total sum and substract the numbers not in range
33-
sumRange =sum;
34-
for (inti =0;i <left;i++) {
35-
sumRange -=nums[i];
36-
}
37-
for (inti =right +1;i <nums.length;i++) {
38-
sumRange -=nums[i];
39-
}
33+
privateintsum(inti) {
34+
intsum =0;
35+
while (i >0) {
36+
sum +=tree[i];
37+
i -= (i & -i);
4038
}
41-
returnsumRange;
39+
returnsum;
40+
}
41+
42+
publicintsumRange(intleft,intright) {
43+
returnsum(right +1) -sum(left);
4244
}
4345
}
46+
47+
/*
48+
* Your NumArray object will be instantiated and called as such:
49+
* NumArray obj = new NumArray(nums);
50+
* obj.update(index,val);
51+
* int param_2 = obj.sumRange(left,right);
52+
*/

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp