[Leetcode] 307. Range Sum query-mutable

Source: Internet
Author: User

Given an integer array nums, find the sum of the elements between indices I and J (iJ), 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:

    1. The array is a modifiable by the update function.
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.