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

Analysis

重点在于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

class NumArray {
private int[] sums;
public NumArray(int[] nums) {
if (nums.length == 0) return;
sums = new int[nums.length];
sums[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sums[i] = sums[i - 1] + nums[i];
}
}
public int sumRange(int i, int j) {
if (i == 0) return sums[j];
return sums[j] - sums[i - 1];
}
}