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]

  1. sumRange(0, 2) -> 1
  2. sumRange(2, 5) -> -1
  3. sumRange(0, 5) -> -3

Note:

  • You may assume that the array does not change.
  • There are many calls to sumRange function.

    分析

令状态f[i]为0到i元素之间的和,则状态转移方程为 f[i] = f[i-1] + nums[i]f[i]本质上是累加和,有了f[i],则范围[i,j]之间的和等于f[j] - f[i-1]

代码

  1. // Range Sum Query - Immutable
  2. public class NumArray {
  3. // Time Complexity: O(n), Space Complexity: O(1)
  4. public NumArray(int[] nums) {
  5. this.f = new int[nums.length];
  6. int sum = 0;
  7. for (int i = 0; i < nums.length; ++i) {
  8. sum += nums[i];
  9. f[i] = sum;
  10. }
  11. }
  12. // Time Complexity: O(1), Space Complexity: O(1)
  13. public int sumRange(int i, int j) {
  14. return f[j] - (i == 0 ? 0 : f[i - 1]);
  15. }
  16. private final int[] f;
  17. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dp/range-sum-query-immutable.html