leetcode Range Sum Query - Mutable
2015-12-01 19:55
344 查看
原题链接:https://leetcode.com/problems/range-sum-query-mutable/
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.
线段树单点更新。。
Description
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:
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 { public: NumArray() = default; NumArray(vector<int> &nums) { n = (int)nums.size(); if (!n) return; arr = new int[n << 2]; built(1, 1, n, nums); } ~NumArray() { delete []arr; } void update(int i, int val) { update(1, 1, n, i + 1, val); } int sumRange(int i, int j) { return sumRange(1, 1, n, i + 1, j + 1); } private: int n, *arr; void built(int root, int l, int r, vector<int> &nums) { if (l == r) { arr[root] = nums[l - 1]; return; } int mid = (l + r) >> 1; built(root << 1, l, mid, nums); built(root << 1 | 1, mid + 1, r, nums); arr[root] = arr[root << 1] + arr[root << 1 | 1]; } void update(int root, int l, int r, int pos, int val) { if (pos > r || pos < l) return; if (pos <= l && pos >= r) { arr[root] = val; return; } int mid = (l + r) >> 1; update(root << 1, l, mid, pos, val); update(root << 1 | 1, mid + 1, r, pos, val); arr[root] = arr[root << 1] + arr[root << 1 | 1]; } int sumRange(int root, int l, int r, int x, int y) { if (x > r || y < l) return 0; if (x <= l && y >= r) return arr[root]; int mid = (l + r) >> 1, ret = 0; ret += sumRange(root << 1, l, mid, x, y); ret += sumRange(root << 1 | 1, mid + 1, r, x, y); return ret; } };
相关文章推荐
- IOS开发之控件之间的继承关系UILable,UIImageView
- UINavigationController属性 & 导航栏透明度影响下边子视图的原点位置
- ios UINavigationController
- String和StringBuilder、StringBuffer的区别?
- 利用协议代理实现导航控制器UINavigationController视图之间的正向传值和反向传值
- 重写系统中的UINavigationController 返回按钮的事件
- .htaccess 中 %{REQUEST_FILENAME} 及其参数的意思
- networkRequest
- QNetworkRequest 请求类
- VC皮肤库之duilib
- directUI
- UESTC 1222 Sudoku
- \backend\models\core\Request
- MediaCodec 编码H264 编码一帧后dequeueOutputBuffer为-1的问题
- 1041. Be Unique (20)
- 理解百度云推送的几个概念
- does not contain bitcode. You must rebuild it with
- Android中的Looper,Handler,Message和MessageQueue
- form builder视图窗口下找不到堆叠视图项
- poj--1904--King's Quest(scc建图)