370 Range Addition
Assume you have an array of lengthninitialized with all0's and are givenkupdate operations.
Each operation is represented as a triplet:[startIndex, endIndex, inc]which increments each element of subarrayA[startIndex ... endIndex](startIndex and endIndex inclusive) withinc.
Return the modified array after allkoperations were executed.
Example:
Explanation:
Hint:
Thinking of using advanced data structures? You are thinking it too complicated.
For each update operation, do you really need to update all elements between i and j?
Update only the first and end element is sufficient.
The optimal time complexity is O(k + n) and uses O(1) extra space.
这题基本做法是,把需要改变的range开始的那个数加上要改变的数字,然后把range结束后一个数减去要改变的数字。最后用一个loop来算prefix sum。这样就能得到最终答案。我多开了一个数组tmp所以空间复杂度不是O(1) 。
Last updated