Range Sum Query - Immutable
Given an integer array nums, find the sum of the elements between indices i and j (i≤j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -
>
1
sumRange(2, 5) -
>
-1
sumRange(0, 5) -
>
-3Note:
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
Was this helpful?