307. Range Sum Query - Mutable
2016-03-22 10:50
555 查看
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.
Subscribe to see which companies asked this question
树状数组,关于树状数组的详情可以参照http://baike.baidu.com/link?url=U7QI5Dr2xEufw9MuPWWTRQQuQCbdg9c5S6vXlDcweVUrT8z9RoQWC0qhjVQJUjPypWTOl4QGwe67QlQqz7u10q
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.
Subscribe to see which companies asked this question
树状数组,关于树状数组的详情可以参照http://baike.baidu.com/link?url=U7QI5Dr2xEufw9MuPWWTRQQuQCbdg9c5S6vXlDcweVUrT8z9RoQWC0qhjVQJUjPypWTOl4QGwe67QlQqz7u10q
public 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 numArray = new NumArray(nums); // numArray.sumRange(0, 1); // numArray.update(1, 10); // numArray.sumRange(1, 2);
相关文章推荐
- seueuQgnisukcatStnemelpmI.225
- how to write order by and limit query in jpa [duplicate]
- Android自动化测试(UiAutomator)简要介绍 - 萧瑟一笑的专栏 - 博客频道 - CSDN.NET
- Crank Storyboard Suite入门(一)
- 【LeetCode】60. Permutation Sequence
- 304. Range Sum Query 2D - Immutable
- 对iOS 9 新增的控件 UIStackView 官方文档的翻译 第四部分
- 187. Repeated DNA Sequences
- 60. Permutation Sequence
- 手机GUI自动化测试介绍 | 有道技术沙龙博客
- C#中怎么生成36位的GUID
- UIViewContentMode各类型效果
- iOS开发~UITableViewCell重用机制总结
- android UI进阶之实现listview的分页加载
- libraries for bitcode must be generated from Xcode Archive or Install build forARM7 解决办法
- DelayQueue 队列
- 《iOS Human Interface Guidelines》——Contact Add Button
- UIStepper
- SQL Interview Questions
- PHP基础之如何调试PHP程序(HBuilder)