【Leetcode】Range Sum Query - Mutable
来源:互联网 发布:淘宝发布山寨机 编辑:程序博客网 时间:2024/05/04 20:14
题目链接:https://leetcode.com/problems/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) -> 9update(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.
思路:
segment tree基础,创建tree用分治,求sum要注意所求的区间和节点区间的关系。
算法:
public class NumArray {Node root = null;public NumArray(int[] nums) {root = create(nums, 0, nums.length - 1);}void update(int i, int val) {update(root, i, val);}public int sumRange(int i, int j) {return sum(root, i, j);}public class Node {int lidx;int ridx;int val;Node lchild;Node rchild;public Node(int lidx, int ridx, int val) {this.lidx = lidx;this.ridx = ridx;this.val = val;}}public Node create(int[] nums, int l, int r) {if (l == r)return new Node(l, r, nums[r]);Node lchild = create(nums, l, (l + r) / 2);Node rchild = create(nums, (l + r) / 2 + 1, r);Node root = new Node(lchild.lidx, rchild.ridx, lchild.val + rchild.val);root.lchild = lchild;root.rchild = rchild;return root;}public int sum(Node root, int l, int r) {if (root.ridx < l || root.lidx > r)// 所求区间与节点区间不相交return 0;if (l <= root.lidx && root.ridx <= r)// 所求区间包含了 节点区间return root.val;return sum(root.lchild, l, r) + sum(root.rchild, l, r);//所求区间和节点区间相交}int diff = 0;// 需要从index叶节点 往上更新的值public void update(Node root, int index, int newVal) {if (root.lidx == root.ridx && index == root.lidx) {// 要更新的叶节点diff = newVal - root.val;root.val = newVal;return;}if (index <= (root.lidx + root.ridx) / 2)update(root.lchild, index, newVal);elseupdate(root.rchild, index, newVal);root.val += diff;}}
0 0
- [LeetCode]Range Sum Query - Mutable
- Range Sum Query - Mutable -leetcode
- leetcode Range Sum Query - Mutable
- Leetcode: Range Sum Query - Mutable
- Leetcode: Range Sum Query - Mutable
- leetcode, Range Sum Query - Mutable
- LeetCode Range Sum Query - Mutable
- leetcode - Range Sum Query - Mutable
- Range Sum Query - Mutable -- Leetcode
- leetcode Range Sum Query-Mutable
- 【Leetcode】Range Sum Query - Mutable
- leetcode之Range Sum Query - Mutable
- LeetCode 题解(289): Range Sum Query - Mutable
- [leetcode-307]Range Sum Query - Mutable(java)
- leetcode 307 : Range Sum Query - Mutable
- [LeetCode 307] Range Sum Query - Mutable
- LeetCode(307) Range Sum Query - Mutable
- leetcode笔记:Range Sum Query - Mutable
- js 数字相加
- bootstrap关闭modal后,如何清空modal里的bootstrapValidator的校验痕迹
- Java程序猿之线程(27)
- 第二周 项目3(2)--体验复杂度---汉诺塔
- MySQL索引常用算法
- 【Leetcode】Range Sum Query - Mutable
- Hibernate之DetachedCriteria类详解
- Android 轮询最佳实践 Service + AlarmManager+Thread
- Storm与Spark Streaming横向对比
- 【第2周 项目2 - 程序的多文件组织】
- web密码修改模态框
- IntelliJ Idea 复制粘贴的问题
- web开发转发和重定向大比拼
- npm 常用操作