标签:
原题链接在这里:https://leetcode.com/problems/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:
题解:
与Range Sum Query - Mutable类似,用到了二维binary index tree.
Time Complexity: builder O(mnlogmn). update O(logmn). sumRange O(logmn). Space : O(mn).
AC Java:
1 public class NumArray { 2 int [] BIT; 3 int [] nums; 4 5 public NumArray(int[] nums) { 6 if(nums == null || nums.length == 0){ 7 return; 8 } 9 BIT = new int[nums.length + 1]; 10 this.nums = new int[nums.length]; 11 for(int i = 0; i<nums.length; i++){ 12 update(i, nums[i]); 13 } 14 } 15 16 void update(int i, int val) { 17 int diff = val - nums[i]; 18 nums[i] = val; 19 for(int j = i+1; j<BIT.length; j += (j&-j)){ 20 BIT[j] += diff; 21 } 22 } 23 24 public int sumRange(int i, int j) { 25 return getSum(j+1) - getSum(i); 26 } 27 private int getSum(int i){ 28 int sum = 0; 29 while(i > 0){ 30 sum += BIT[i]; 31 i -= (i & -i); 32 } 33 return sum; 34 } 35 } 36 37 38 // Your NumArray object will be instantiated and called as such: 39 // NumArray numArray = new NumArray(nums); 40 // numArray.sumRange(0, 1); 41 // numArray.update(1, 10); 42 // numArray.sumRange(1, 2);
LeetCode Range Sum Query - Mutable
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/5246473.html