https://leetcode-cn.com/problems/range-sum-query-mutable/
其中一类查询要求 更新 数组nums下标对应的值
另一类查询要求返回数组nums中索引left和索引right之间(包含)的nums元素的 和,其中left <= right
实现 NumArray 类:
NumArray(int[] nums) 用整数数组 nums 初始化对象
void update(int index, int val) 将 nums[index] 的值 更新 为 val
int sumRange(int left, int right) 返回数组nums中索引left和索引right之间(包含)的nums元素的 和(即,nums[left] + nums[left + 1], ..., nums[right])
示例 1:
输入:
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
输出:
[null, 9, null, 8]
解释:
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // 返回 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1,2,5]
numArray.sumRange(0, 2); // 返回 1 + 2 + 5 = 8
方法一:线性树
class NumArray {
int[] nums;
int[] tree;
int n;
public NumArray(int[] nums) {
this.nums = nums;
n = nums.length;
if (n == 0) {
return;
}
tree = new int[n * 4];
buildTree(0, 0, n - 1);
}
void buildTree(int node, int start, int end) {
if (start == end) {
tree[node] = nums[start];
return;
}
int mid = (end + start) / 2 + start;
int left = node * 2 + 1;
int right = node * 2 + 2;
buildTree(left, start, mid);
buildTree(right, mid + 1, end);
tree[node] = tree[left] + tree[right];
}
public void update(int index, int val) {
updateTree(index, 0, val, 0, n - 1);
}
public void updateTree(int idx, int node, int val, int start, int end) {
if (start > end) {
return;
}
if (start == end) {
nums[idx] = val;
tree[node] = val;
} else {
int mid = (start + end) >> 1;
int left = node * 2 + 1;
int right = node * 2 + 2;
if (idx >= start && idx <= mid) {
updateTree(idx, left, val, start, mid);
} else {
updateTree(idx, right, val, mid + 1, end);
}
tree[node] = tree[left] + tree[right];
}
}
public int sumRange(int left, int right) {
return query(left, right, 0, 0, n - 1);
}
public int query(int l, int r, int node, int start, int end) {
if (l > end || r < start) {
return 0;
}
if (start == end) {
return tree[node];
}
if (l <= start && r <= end) {
return tree[node];
} else {
int mid = (start + end) >> 1;
int left = node * 2 + 1;
int right = node * 2 + 2;
int ls = query(l, r, left, start, mid);
int rs = query(l, r, right, end, mid + 1);
return ls + rs;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。