Range Sum Query - Immutable
Given an integer array nums, find the sum of the elements between indices i and j (i≤j), inclusive.
Example:
Note:
You may assume that the array does not change.
There are many calls to sumRange function.
Analysis
参考:https://leetcode.com/problems/range-sum-query-immutable/solution/
重点在于sumRange()
需要较高的效率,比如O(1)的时间复杂度。因此在初始化时要进行处理,最直觉的就是关于range sum,可以新建数组存入[0, i)
的sums
,这样需要[i, j]
的时候,sums[j + 1] - sums[i]
即可。小技巧是生成nums.length + 1的sums[],而sums[i]
代表了[0, i)
,也就是不包含i
的和。
Solution
Last updated