导航
导航
文章目录
  1. 题目
  2. 翻译

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

翻译

给出一个整型数组nums,计算下标在i到j (i ≤ j,包括i、j)之间的元素之和。
例如:
给出 nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
注意:
你可以认为数组是不变的。
会多次调用sumRange函数。

构造从第一个元素开始,到后面所有元素的和的记录sums。
当i等于0时,直接返回sums[j];
当i不等于0时,返回sums[j] - sums[i - 1],
例如,sumRange(2, 5) = sumRange(0, 5) - sumRange(0, 1) = sums[5] - sums[1]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class NumArray {

private int[] sums;

public NumArray(int[] nums) {
sums = new int[nums.length];
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
sums[i] = sum;
}
}

public int sumRange(int i, int j) {
if (i == 0) return sums[j];
return sums[j] - sums[i - 1];
}
}

1
2
3
4
// Your NumArray object will be instantiated and called as such:
// NumArray numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);