207.Interval Sum II
Description:
在类的构造函数中给一个整数数组, 实现两个方法 query(start, end)
和 modify(index, value)
:
- 对于 query(start, end), 返回数组中下标 start 到 end的 和。
- 对于 modify(index, value), 修改数组中下标为 index上的数为 value.
Explanation:
给定数组 A = [1,2,7,8,5]
.
query(0, 2)
, 返回10
.modify(0, 4)
, 将 A[0] 修改为 4.query(0, 1)
, 返回6
.modify(2, 1)
, 将 A[2] 修改为 1.query(2, 4)
, 返回14
.
Solution:
解题之前整理了一下关于线段树的三道题,分别是线段树的构造、查询和修改。可以参考http://blog.csdn.net/sunday0904/article/details/73928989
首先设置类SegmentTreeNode,添加域sum,start和end,并添加左、右子树。
然后将对于数组的操作,转化成对线段树的操作。
线段树的初始化(构造):
采用递归的方法,构造线段树,并且计算当前节点的sum。
查询:
对数组的查询转换成对线段树的查询,采用了分治法。
在线段树的查询中使用了递归的方法。
修改:
对数组的修改转换成对线段树的修改,采用了分治法。
某一个节点值得修改,会更新所有父节点的sum。
在线段树的修改中使用了递归的方法。
构造函数Solution(int[] A) ----> create();
查询 query() ----> querySegment();
修改 modify() ----> modifySegment();
public class Solution {
/* you may need to use some attributes here */
class SegmentTreeNode{
int start;
int end;
long sum;
SegmentTreeNode left;
SegmentTreeNode right;
SegmentTreeNode(int start , int end){
this.start = start;
this.end = end;
this.sum = 0;
this.left = null;
this.right = null;
}
}
SegmentTreeNode root;
/**
* @param A: An integer array
*/
public Solution(int[] A) {
// write your code here
if(A == null || A.length == 0) return;
root = create(A , 0 , A.length - 1);
}
public SegmentTreeNode create(int[] A , int start , int end){
SegmentTreeNode current = new SegmentTreeNode(start , end);
if(start == end){
current.sum = A[start];
}else{
int mid = start + (end - start)/2;
current.left = create(A , start , mid);
current.right = create(A , mid + 1 , end);
current.sum = current.left.sum + current.right.sum;
}
return current;
}
/**
* @param start, end: Indices
* @return: The sum from start to end
*/
public long query(int start, int end) {
// write your code here
return querySegment(root , start , end);
}
public long querySegment(SegmentTreeNode current , int start , int end){
if(start == current.start && end == current.end){
return current.sum;
}
int mid = current.start + (current.end - current.start)/2;
if(start > mid){
return querySegment(current.right , start , end);
}else if(end <= mid){
return querySegment(current.left , start , end);
}else{
return querySegment(current.left , start , mid) + querySegment(current.right , mid + 1 , end);
}
}
/**
* @param index, value: modify A[index] to value.
*/
public void modify(int index, int value) {
// write your code here
modifySegment(root, index , value);
}
public void modifySegment(SegmentTreeNode current , int index , int value){
if(current.start == current.end){
current.sum = value;
return;
}
int mid = current.start + (current.end - current.start)/2;
if(index <= mid){
modifySegment(current.left , index , value);
}else{
modifySegment(current.right , index , value);
}
current.sum = current.left.sum + current.right.sum;
}
}