aboutsummaryrefslogtreecommitdiff
path: root/other/range_sum_query_mutable.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/range_sum_query_mutable.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/range_sum_query_mutable.cpp')
-rw-r--r--other/range_sum_query_mutable.cpp61
1 files changed, 61 insertions, 0 deletions
diff --git a/other/range_sum_query_mutable.cpp b/other/range_sum_query_mutable.cpp
new file mode 100644
index 0000000..cdc0230
--- /dev/null
+++ b/other/range_sum_query_mutable.cpp
@@ -0,0 +1,61 @@
+#include "leetcode.h"
+
+struct segNode {
+ int start, end, sum;
+ segNode *left, *right;
+ segNode(int a, int b)
+ : start(a), end(b), sum(0), left(nullptr), right(nullptr) {}
+};
+
+class NumArray {
+public:
+ segNode *root;
+ NumArray(vector<int> &nums) { root = buildTree(nums, 0, nums.size() - 1); }
+ void update(int index, int val) { modifyTree(index, val, root); }
+ int sumRange(int left, int right) { return queryTree(left, right, root); }
+
+private:
+ segNode *buildTree(vector<int> &nums, int start, int end) {
+ if (start > end)
+ return nullptr;
+ segNode *root = new segNode(start, end);
+ if (start == end) {
+ root->sum = nums[start];
+ return root;
+ }
+ int mid = start + (end - start) / 2;
+ root->left = buildTree(nums, start, mid);
+ root->right = buildTree(nums, mid + 1, end);
+ root->sum = root->left->sum + root->right->sum;
+ return root;
+ }
+ int modifyTree(int i, int val, segNode *root) {
+ if (root == nullptr)
+ return 0;
+ int diff;
+ if (root->start == i && root->end == i) {
+ diff = val - root->sum;
+ root->sum = val;
+ return diff;
+ }
+ int mid = (root->start + root->end) / 2;
+ if (i > mid)
+ diff = modifyTree(i, val, root->right);
+ else
+ diff = modifyTree(i, val, root->left);
+ root->sum = root->sum + diff;
+ return diff;
+ }
+ int queryTree(int i, int j, segNode *root) {
+ if (root == nullptr)
+ return 0;
+ if (root->start == i && root->end == j)
+ return root->sum;
+ int mid = (root->start + root->end) / 2;
+ if (i > mid)
+ return queryTree(i, j, root->right);
+ if (j <= mid)
+ return queryTree(i, j, root->left);
+ return queryTree(i, mid, root->left) + queryTree(mid + 1, j, root->right);
+ }
+};