Range Sum Query - Mutable
2017-04-05 20:15
302 查看
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:
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
Java代码:
public class NumArray {
int[] bitset;
int[] nums;
void init(int i,int val){
i++;
while(i<bitset.length){
bitset[i]+=val;
i+=(i&-i);
}
}
int getsum(int i){
int sum=0;
i++;
while(i>0){
sum+=bitset[i];
i-=(i&-i);
}
return sum;
}
public NumArray(int[] nums) {
bitset=new int[nums.length+1];
for(int i=0;i<nums.length;i++)init(i,nums[i]);
this.nums=nums;
}
public void update(int i, int val) {
int diff=val-nums[i];
nums[i]=val;
init(i,diff);
}
public int sumRange(int i, int j) {
return getsum(j)-getsum(i-1);
}
}
思路分析:使用树状数组,其中求index的低位用(index&-index)
时间复杂度:
update为O(Log(N))
init为O(N*Log(N))
sumRange为O(Log(N))
getSum为O(Log(N))
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:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
Java代码:
public class NumArray {
int[] bitset;
int[] nums;
void init(int i,int val){
i++;
while(i<bitset.length){
bitset[i]+=val;
i+=(i&-i);
}
}
int getsum(int i){
int sum=0;
i++;
while(i>0){
sum+=bitset[i];
i-=(i&-i);
}
return sum;
}
public NumArray(int[] nums) {
bitset=new int[nums.length+1];
for(int i=0;i<nums.length;i++)init(i,nums[i]);
this.nums=nums;
}
public void update(int i, int val) {
int diff=val-nums[i];
nums[i]=val;
init(i,diff);
}
public int sumRange(int i, int j) {
return getsum(j)-getsum(i-1);
}
}
思路分析:使用树状数组,其中求index的低位用(index&-index)
时间复杂度:
update为O(Log(N))
init为O(N*Log(N))
sumRange为O(Log(N))
getSum为O(Log(N))
相关文章推荐
- LeetCode[307]Range Sum Query - Mutable(Java)
- Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- leetcode 307. Range Sum Query - Mutable
- [leetcode] 307. Range Sum Query - Mutable
- leetcode Range Sum Query-Mutable
- 【Leetcode】Range Sum Query - Mutable
- leetcode - Range Sum Query - Mutable
- leecode_307 Range Sum Query - Mutable
- Range_Sum_Query_Mutable
- leetcode之Range Sum Query - Mutable
- leetcode 307 : Range Sum Query - Mutable
- Leetcode 307: Range Sum Query - Mutable 之BIT
- LeetCode "Range Sum Query - Mutable"
- LeetCode "Range Sum Query 2D - Mutable"
- [LeetCode] Range Sum Query 2D - Mutable 二维区域和检索 - 可变
- (LeetCode 307) Range Sum Query - Mutable(Segment Tree)
- Range Sum Query - Mutable:对区域内的值经常改变的数组求区域内的和 线段数
- [LeetCode] Range Sum Query - Mutable 区域和检索 - 可变
- LeetCode Range Sum Query - Mutable