2017年12月11日 星期一

[LeetCode] 303. Range Sum Query - Immutable

轉自LeetCode

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:
  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.
<Solution>

這題最需要注意的地方是,題目說會呼叫非常多次的 sumRange

所以如果每次再去計算和,很容易TLE

想法如下
  • 在內部儲存一個 sum array,定義是 sum[n] = nums[n-1] + sum[n-1],sum[0] = 0
  • 這樣當要計算 nums[i] + ... + nums[j],就等於 sum[j+1] - sum[i]
code如下

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);
*/

沒有留言:

張貼留言