标签:fun 数组 gap tin upd sse may note bsp
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), 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 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
标签:fun 数组 gap tin upd sse may note bsp
原文地址:http://www.cnblogs.com/wzj4858/p/7731940.html