您的位置:首页 > 产品设计 > UI/UE

307. Range Sum Query - Mutable

2017-02-14 22:03 190 查看
问题链接:点击打开链接

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.
Solution:

assume update and sumRange function is distributed evenly, we need O(lgn) complexity for both functions.

Could use binary tree achieve this. Use segment tree to store, the node has left to right range, and the range sum. For update operation, need to find the node and update all node which range include the position. For sumRange operation, need to find the nodes
which range could consist the sumrange you are looking for.

public class NumArray {

class TreeNode {
int start = 0;
int end = 0;
int sum = 0;
TreeNode left = null;
TreeNode right = null;
}

TreeNode root = null;
public void init(int[] nums) {
if(nums == null || nums.length == 0) return;
this.root = buildTree(0, nums.length-1, nums);
}

public TreeNode buildTree(int start, int end, int[] data) {
TreeNode t = new TreeNode();
t.start = start;
t.end = end;
if(start == end) {
t.sum = data[start];
return t;
}
int mid = start + (end-start)/2;
t.left = buildTree(start, mid, data);
t.right = buildTree(mid+1, end, data);
t.sum = t.left.sum + t.right.sum;
return t;
}

public NumArray(int[] nums) {
init(nums);
}

public void updateTree(TreeNode node, int index, int val) {
if(node == null) return;
if(node.start == node.end) {
node.sum = val;
return;
}
int mid = node.start + (node.end - node.start)/2;
if(index<=mid) {
updateTree(node.left, index, val);
}else {
updateTree(node.right, index, val);
}
node.sum = node.left.sum + node.right.sum;
}

void update(int i, int val) {
updateTree(this.root, i, val);
}

public int queryTree(TreeNode node, int left, int right) {
if(node == null) return 0;
if(node.start == left && node.end == right) return node.sum;
int mid = node.start + (node.end - node.start)/2;
if(mid>=right) {
return queryTree(node.left, left, right);
}else if(mid<left) {
return queryTree(node.right, left, right);
}else {
return queryTree(node.left, left, mid) + queryTree(node.right, mid+1, right);
}
}

public int sumRange(int i, int j) {
return queryTree(root, i, j);
}
}

/**
* 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);
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode