Skip to content

Commit

Permalink
Improved task 307
Browse files Browse the repository at this point in the history
  • Loading branch information
javadev authored Mar 31, 2023
1 parent 639871f commit b7d8556
Showing 1 changed file with 33 additions and 24 deletions.
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);
*/

0 comments on commit b7d8556

Please sign in to comment.