-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
33 additions
and
24 deletions.
There are no files selected for viewing
57 changes: 33 additions & 24 deletions
57
src/main/java/g0301_0400/s0307_range_sum_query_mutable/NumArray.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,43 +1,52 @@ | ||
package g0301_0400.s0307_range_sum_query_mutable; | ||
|
||
// #Medium #Array #Design #Segment_Tree #Binary_Indexed_Tree | ||
// #2022_07_07_Time_99_ms_(88.96%)_Space_138.9_MB_(5.17%) | ||
// #2023_03_31_Time_92_ms_(90.27%)_Space_75.3_MB_(16.68%) | ||
|
||
public class NumArray { | ||
private int[] tree; | ||
private int[] nums; | ||
private int sum; | ||
|
||
public NumArray(int[] nums) { | ||
tree = new int[nums.length + 1]; | ||
this.nums = nums; | ||
sum = 0; | ||
for (int num : nums) { | ||
sum += num; | ||
// copy the array into the tree | ||
System.arraycopy(nums, 0, tree, 1, nums.length); | ||
for (int i = 1; i < tree.length; i++) { | ||
int parent = i + (i & -i); | ||
if (parent < tree.length) { | ||
tree[parent] += tree[i]; | ||
} | ||
} | ||
} | ||
|
||
public void update(int index, int val) { | ||
sum -= nums[index] - val; | ||
int currValue = nums[index]; | ||
nums[index] = val; | ||
index++; | ||
while (index < tree.length) { | ||
tree[index] = tree[index] - currValue + val; | ||
index = index + (index & -index); | ||
} | ||
} | ||
|
||
public int sumRange(int left, int right) { | ||
int sumRange = 0; | ||
if ((right - left) < nums.length / 2) { | ||
// Array to sum is less than half | ||
for (int i = left; i <= right; i++) { | ||
sumRange += nums[i]; | ||
} | ||
} else { | ||
// Array to sum is more than half | ||
// Better to take total sum and substract the numbers not in range | ||
sumRange = sum; | ||
for (int i = 0; i < left; i++) { | ||
sumRange -= nums[i]; | ||
} | ||
for (int i = right + 1; i < nums.length; i++) { | ||
sumRange -= nums[i]; | ||
} | ||
private int sum(int i) { | ||
int sum = 0; | ||
while (i > 0) { | ||
sum += tree[i]; | ||
i -= (i & -i); | ||
} | ||
return sumRange; | ||
return sum; | ||
} | ||
|
||
public int sumRange(int left, int right) { | ||
return sum(right + 1) - sum(left); | ||
} | ||
} | ||
|
||
/* | ||
* Your NumArray object will be instantiated and called as such: | ||
* NumArray obj = new NumArray(nums); | ||
* obj.update(index,val); | ||
* int param_2 = obj.sumRange(left,right); | ||
*/ |