leetcode解题: Range Sum Query - immutable (303)

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.

解法: Memorization/DP with O(1) time and O(N) space

就是Subarray类题目的变形,求subarray sum首先要想到前缀和数组。维护一个cumulative sum,然后每次计算i到j的和的时候就是sum[j] - sum[i-1],花费时间是O(1)要注意的是下边界越界的处理。
dp[i] = (k - 1) * (dp[i -1] + dp[i - 2])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class NumArray {
int[] cumsum = null;
public NumArray(int[] nums) {
// calculate the cumulative sum O(N)
// exception handling
if (nums == null || nums.length == 0) {
return;
}
cumsum = new int[nums.length];
cumsum[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
cumsum[i] = cumsum[i - 1] + nums[i];
}
}
public int sumRange(int i, int j) {
// Array access: O(1)
if (cumsum == null) {
return 0;
}
if (i == 0) {
return cumsum[j];
}
return cumsum[j] - cumsum[i - 1];
}
}
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);