307. Range Sum Query - Mutable

Posted andywu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了307. Range Sum Query - Mutable相关的知识,希望对你有一定的参考价值。

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. 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的主要内容,如果未能解决你的问题,请参考以下文章

307 Range Sum Query - Mutable

307. Range Sum Query - Mutable

Leetcode 307. Range Sum Query - Mutable

307. Range Sum Query - Mutable

LeetCode - 307. Range Sum Query - Mutable

307. Range Sum Query - Mutable查询求和的范围(可变)