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 on index i to Val.
Example:
Given nums = [1, 3, 5]sumrange (0, 2), 9update (1, 2) sumrange (0, 2), 8
Note:
- The array is a modifiable by the update function.
- Assume the number of calls to update and sumrange function is distributed evenly.
Subscribe to see which companies asked this question
Solution:
Using values and sums to record the first n and, respectively, Nums and Nums, and, when update, the index of the sums is greater than I will change.
1 classNumarray2 {3 Public:4Numarray (vector<int> &nums)5 {6Sums.push_back (0);7 for(inti =0; I < nums.size (); i++)8 {9Sums.push_back (Sums[i] +nums[i]);Ten Values.push_back (Nums[i]); One } A } - - voidUpdateintIintval) the { - intdiff = Val-Values[i]; - for(intK = i +1; K < Sums.size (); k++) -SUMS[K] = Sums[k] +diff; +Values[i] =Val; - } + A intSumrange (intIintj) at { - returnSums[j +1] -Sums[i]; - } - Private: -vector<int>sums; -vector<int>values; in};
[Leetcode] 307. Range Sum query-mutable