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) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
這題最需要注意的地方是,題目說會呼叫非常多次的 sumRange
所以如果每次再去計算和,很容易TLE
想法如下
- 在內部儲存一個 sum array,定義是 sum[n] = nums[n-1] + sum[n-1],sum[0] = 0
- 這樣當要計算 nums[i] + ... + nums[j],就等於 sum[j+1] - sum[i]
沒有留言:
張貼留言