[LeetCode] 307. 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:
- The array is only modifiable by the update function.
- You may assume the number of calls to update and sumRange function is distributed evenly.
问题:给定一个固定长度的数组,可以更新元素的值,求给定子数组的元素和。求和与更新操作交替进行。
解决方案
方案1,每次求和,直接遍历子数组进行求和。每次更新,直接根据下标更新元素值。求和操作时间复杂度为 O(n), 更新操作时间复杂度为O(1)
方案2,采用线段树存储原数组以及中间结果。
例子:输入数组{1, 3, 5, 7, 9, 11} 对应的线段树数据结构如下,叶子节点存储输入数组的元素,非叶子节点存储一个区域的和。

线段树是一个 full binary tree,可以用数组来存储。数组下标和线段树的节点之间的关系如下:
对于节点 i,
- 其左子节点下标为 i*2+1
- 其右节点下标为 i*2+2
- 其父亲节点下标为 (i-1)/2
基于数组的线段树表示例子如下:

求和思路:计算子数组[l, r] 的和时,对于给定节点 node 有:
- 如果节点 node 代表的范围在 [l, r] 之内,则返回节点 node 的值
- 如果节点 node 代表的范围完全不在 [l, r] 之内,则返回 0
- 其他情况,节点 node 代表的范围一部分在 [l, r]之内,一部分不在之内,则对于节点 node 的左右子节点分别应用该规则进行处理。
更新思路:根据给定的下标,更新下标对应元素在线段树的叶子节点,并更新从该叶子节点到根节点路径上的所有祖先节点。
构建线段树:根据输入数组,求得线段树需要的节点值。例如 {1, 3, 5, 7, 9, 11, 4, 12, 20, 16, 36}
对节点值进行反序处理,则得到基于数组结构的线段树。例如 {36, 16, 20, 12, 4, 11, 9, 7, 5, 3, 1}
代码实现如下:
#include <vector>
using namespace std;struct TreeNode{
int val;
pair<int, int> idxRange; TreeNode(int val, int lRange, int rRange){
this->val = val;
this->idxRange = make_pair(lRange, rRange);
}
}; class NumArray { vector<int> nums;
vector<TreeNode *> nodesVec;
vector<TreeNode *> treeVec; /**
* calculate the nodes of the segment tree based on the input values in nums
*/
void calculateNodes(){
for(int i=; i < nums.size(); i++){
TreeNode *tn = new TreeNode(nums[i], i, i);
this->nodesVec.push_back(tn);
} for(int i =; i + < nodesVec.size(); i+=){
int val = nodesVec[i]->val + nodesVec[i+]->val;
int l = min(nodesVec[i]->idxRange.first, nodesVec[i+]->idxRange.first);
int r = max(nodesVec[i]->idxRange.second, nodesVec[i+]->idxRange.second);
TreeNode *tn = new TreeNode(val, l, r);
nodesVec.push_back(tn);
}
} /**
* build segment tree base on Vector.
* For node i,
* the left child index: i * 2 + 1
* the right child index: i * 2 + 2
* the parent index: (i - 1)/2
*/
void buildVectorBasedSegmentTree(){
for(int i=nodesVec.size() - ; i >= ; i--){
treeVec.push_back(nodesVec[i]);
}
} public:
NumArray(){}
virtual ~NumArray(){} /**
* initialization
*/
NumArray(vector<int> nums){
this->nums = nums;
calculateNodes();
buildVectorBasedSegmentTree();
} /**
* update the value of the node in the index i in treeVec
*/
void update(int i, int val){
int leafIdx = treeVec.size() - ( + i );
int diff = val - treeVec[leafIdx]->val;
updateNodes(leafIdx, diff);
} /**
* update the value of nodes in interval tree(segment tree) with the diff recursively.
*/
void updateNodes(int idx, int diff){
treeVec[idx]->val += diff;
if(idx > ){
idx = (idx -) / ;
updateNodes(idx, diff);
}
} int sumRange(int i, int j){
return getSum(, i, j);
} /**
* check the node in i-th index in treeVec, to calculate the sum of leaf
*/
int getSum(int nodeIdx, int rangeL, int rangeR){
TreeNode* node = treeVec[nodeIdx];
if (rangeL <= node->idxRange.first && node->idxRange.second <= rangeR){
return node->val;
} if (node->idxRange.second < rangeL || rangeR < node->idxRange.first){
return ;
}
int nodeIdxL = nodeIdx * + ;
int nodeIdxR = nodeIdx * + ;
return getSum(nodeIdxL, rangeL, rangeR) + getSum(nodeIdxR, rangeL, rangeR);
}
};
Reference:
Segment Tree | Set 1 (Sum of given range), geeksforgeeks
[LeetCode] 307. Range Sum Query - Mutable 解题思路的更多相关文章
- [LeetCode] 307. Range Sum Query - Mutable 区域和检索 - 可变
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- leetcode@ [307] Range Sum Query - Mutable / 线段树模板
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- LeetCode - 307. Range Sum Query - Mutable
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- leetcode 307. Range Sum Query - Mutable(树状数组)
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive ...
- 【刷题-LeetCode】307. Range Sum Query - Mutable
Range Sum Query - Mutable Given an integer array nums, find the sum of the elements between indices ...
- [Leetcode Week16]Range Sum Query - Mutable
Range Sum Query - Mutable 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/range-sum-query-mutable/de ...
- 【leetcode】307. Range Sum Query - Mutable
题目如下: 解题思路:就三个字-线段树.这个题目是线段树用法最经典的场景. 代码如下: class NumArray(object): def __init__(self, nums): " ...
- 307. Range Sum Query - Mutable
题目: Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclu ...
- leetcode 307 Range Sum Query
问题描述:给定一序列,求任意区间(i, j)的元素和:修改任意一元素,实现快速更新 树状数组 树状数组的主要特点是生成一棵树,树的高度为logN.每一层的高度为k,分布在这一层的序列元素索引的二进制表 ...
随机推荐
- docker修改容器gogs时区时间
问题描述: 公司内部搭建了一个gogs-git,是用docker部署的,但是发现提交的代码什么的时间跟服务器时间不一致 提交上去的世界是UTC时间不是中国的时间CST,相当于慢了8个小时 1.dock ...
- trap命令的实战用法
trap命令: trap命令是专用于捕捉信号的.比如像ctrl+c发送给终端的中断信号等等.在捕捉到信号之后,可以进行一系列的操作. 用法:trap 'COMMAND' INT COMMAND表示t ...
- oracle数据库用户基本操作
每个数据库都有一系列的用户,为了访问数据库,用户必须使用用户名等信息先连接上数据库实例,oracle数据库提供了多种方式来管理用户安全.创建用户的时候,可以通过授权等操作来限制用户能访问的资源以及一些 ...
- python分包写入文件,写入固定字节内容,当包达到指定大小时继续写入新文件
第6行通过 for 循环控制生成 .log 文件的数量 第8行,如果该文件存在时先进行清空,然后再进行写入操作 第13行,将文件大小的单位转为MB 第14行,如果文件大小超过1MB时,跳出当前循环,重 ...
- centos 上安装phpstorm
phpstorm在centos上运行依赖JDK,所以先安装JDK环境. 假如是centos自带的openjdk,直接卸载,不支持phpstorm. 下载jdk-7u45-linux-i586.tar. ...
- Java面试之五大框架的理解
五大框架(springMVC,struts2,spring,mybatis,hibernate) 说说你对springMVC框架的理解? 简要口述(如果感觉说的少可以在完整答案里面挑几条说) Spri ...
- 捕获海康威视IPCamera图像,转成OpenCV能够处理的图像(二)
海康威视IPCamera图像捕获 捕获海康威视IPCamera图像.转成OpenCV能够处理的IplImage图像(一) 捕获海康威视IPCamera图像.转成OpenCV能够处理的IplImage图 ...
- IDEA多线程下多个线程切换断点运行调试的技巧
多线程调试设置可以参考:http://www.cnblogs.com/leodaxin/p/7710630.html 1 断点设置如图: 2 测试代码,然后进行debug package com.da ...
- JavaScript中的typeof操作符用法实例
在Web前端开发中,我们经常需要判断变量的数据类型.鉴于ECMAScript是松散类型的,因此需要有一种手段来检测给定变量的数据类型——typeof就是负责提供这方便信息的操作符. 对一个值使用t ...
- Domain Adaptation (3)论文翻译
Abstract The recent success of deep neural networks relies on massive amounts of labeled data. For a ...