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]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NumArray { | |
private int[] sumArray; | |
public NumArray(int[] nums) { | |
sumArray = new int[nums.length+1]; | |
for(int i = 1; i < sumArray.length; ++i) { | |
sumArray[i] = nums[i-1] + sumArray[i-1]; | |
} | |
} | |
public int sumRange(int i, int j) { | |
return sumArray[j+1] - sumArray[i]; | |
} | |
} | |
/** | |
* Your NumArray object will be instantiated and called as such: | |
* NumArray obj = new NumArray(nums); | |
* int param_1 = obj.sumRange(i,j); | |
*/ |
沒有留言:
張貼留言