307. Range Sum Query
来源:互联网 发布:qq空间病毒式营销源码 编辑:程序博客网 时间:2024/06/02 03:05
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) -> 9update(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.
class NumArray { int[] processed; int[] nums; int length; public NumArray(int[] nums) { length = nums.length; processed = new int[length+1]; this.nums = nums; //init processed for(int i = 1;i<=length;i++){ int sum = 0; int count = 1; int counter = lowBit(i); while(count <= counter){ sum += nums[i-count]; count++; } processed[i] = sum; } } void update(int i, int val) { //更新树状数组 int gap = val - nums[i]; nums[i] = val; int index = i+1; while(index <= length){ processed[index] += gap; index += lowBit(index); } } public int sumRange(int i, int j) { return sum(j+1) - sum(i); } private int sum(int index){ int sum = 0; while(index > 0){ sum += processed[index]; index -= lowBit(index); } return sum; } private int lowBit(int index){ return index & (-index); }}/** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * obj.update(i,val); * int param_2 = obj.sumRange(i,j); */
阅读全文
0 0
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable**
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable
- 307. Range Sum Query - Mutable.
- html_AngularJs简单使用
- JAVA语言程序设计 基础篇 读书笔记(前两章)
- Laravel学习1-创建项目
- zookeeper 启动失败
- PHP 与 mysqli扩展 实现用户创建 查询 更新以及删除
- 307. Range Sum Query
- Java中如何遍历Map对象的4种方法
- JavaScript 对象的使用
- 使用WordPress搭建基于LAMP架构的博客平台
- HDU1166:敌兵布阵(线段树单点更新,区间查询)
- JPA原生sql查询
- 单例模式
- LeetCode 66. Plus One
- KMP算法