1. 程式人生 > >307. Range Sum Query - Mutable

307. Range Sum Query - Mutable

indices mutable counter num index 二維 mod mar bit

Given an integer array nums, find the sum of the elements between indices i and j (ij), inclusive.

The update(i, val) function modifies nums by updating the element at index i to val.

Example:

Given nums = [1, 3, 5]

sumRange(0, 2) -> 9
update(1, 2)
sumRange(0, 2) -> 8

Note:

  1. The array is only modifiable by the update
    function.
  2. You may assume the number of calls to update and sumRange function is distributed evenly.

含義:給你提供一個二維數組,然後求指定下標之間的數之和,已知數組中的值可以更新,並且更新和求和操作會被頻繁調用

 1 class NumArray {
 2 
 3     int[] processed;
 4     int[] nums;
 5     int length;
 6     public NumArray(int[] nums) {
 7         length = nums.length;
8 processed = new int[length+1]; 9 this.nums = nums; 10 11 //init processed 12 for(int i = 1;i<=length;i++){ 13 int sum = 0; 14 int count = 1; 15 int counter = lowBit(i); 16 17 while(count <= counter){ 18 sum += nums[i-count];
19 count++; 20 } 21 processed[i] = sum; 22 } 23 } 24 25 public void update(int i, int val) { 26 //更新樹狀數組 27 int gap = val - nums[i]; 28 nums[i] = val; 29 30 int index = i+1; 31 while(index <= length){ 32 processed[index] += gap; 33 index += lowBit(index); 34 } 35 } 36 37 public int sumRange(int i, int j) { 38 return sum(j+1) - sum(i); 39 } 40 41 private int sum(int index){ 42 int sum = 0; 43 while(index > 0){ 44 sum += processed[index]; 45 index -= lowBit(index); 46 } 47 return sum; 48 } 49 private int lowBit(int index){ 50 return index & (-index); 51 } 52 } 53 54 /** 55 * Your NumArray object will be instantiated and called as such: 56 * NumArray obj = new NumArray(nums); 57 * obj.update(i,val); 58 * int param_2 = obj.sumRange(i,j); 59 */

307. Range Sum Query - Mutable