Leetcode Note: Range Sum Query-Mutable
I. Description
Given an integer arraynums, Find the sum of the elements between indicesiAndj (i ≤ j), Intrusive.
Theupdate(i, val)Function modifiesnumsBy updating the element at indexiToval.
Example:
Givennums = [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 callto update and sumRange function is distributed evenly.
Ii. Question Analysis
This topic is more difficult than the Range Sum Query-Immutable question. You must be able to modify the elements of the array after you input the array nums, and modify only one element at a time. We also need to implement the function of finding a range and of arrays.
If you make a slight improvement in the practice of one question, you can implement the function, but it will time out.
After reading some articles, I found that the original classic practice (including the previous question) is to useTree ArrayTo maintain this array nums, its insertion and query can achieve O (logn) Complexity, very clever.
Iii. Sample Code
// Timeout class NumArray {public: NumArray (vector
& Nums) {if (nums. empty () return; else {sums. push_back (nums [0]); // obtain the length of a given series. int len = nums. size (); for (int I = 1; I <len; ++ I) sums. push_back (sums [I-1] + nums [I]) ;}} void update (int I, int val) {for (int k = I; k <nums. size (); ++ k) sums [k] + = (val-nums [I]); nums [I] = val;} int sumRange (int I, int j) {return sums [j]-sums [I-1];} private: vector
Nums; // stores series and vector
Sums ;}; // Your NumArray object will be instantiated and called as such: // NumArray numArray (nums); // numArray. sumRange (0, 1); // numArray. update (1, 10); // numArray. sumRange (1, 2 );
// The Code AC implemented using a tree array. The complexity is O (logn) class NumArray {private: vector
C; vector
M_nums; public: NumArray (vector
& Nums) {c. resize (nums. size () + 1); m_nums = nums; for (int I = 0; I <nums. size (); I ++) {add (I + 1, nums [I]) ;}} int lowbit (int pos) {return pos & (-pos );} void add (int pos, int value) {while (pos <c. size () {c [pos] + = value; pos + = lowbit (pos) ;}} int sum (int pos) {int res = 0; while (pos> 0) {res + = c [pos]; pos-= lowbit (pos);} return res;} void update (int I, int val) {int ori = m_nums [I]; int delta = val-ori; m_nums [I] = val; add (I + 1, delta);} int sumRange (int I, int j) {return sum (j + 1)-sum (I) ;}; // Your NumArray object will be instantiated and called as such: // NumArray numArray (nums); // numArray. sumRange (0, 1); // numArray. update (1, 10); // numArray. sumRange (1, 2 );
Iv. Summary
I have heard of it before. This is the first time I have used a tree array. This is a good idea for maintaining arrays and requires in-depth study!