`

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.

题目的意思是给定一个数组,如果调用sumRange(i, j) 就返回(i, j)之间 所有元素的和,题目Note中提到sumRange会被调用好多次,这句话的意思就是不希望我们每次都计算从i到j之间的和,这样会浪费很多时间。我们就需要先计算好每个区间的和,然后在调用sumRange后直接返回结果,不需要每次都计算。代码如下:
public class NumArray {
    int[] sumArray;
    public NumArray(int[] nums) {
        sumArray = new int[nums.length + 1];
        for(int i = 1; i <= nums.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 numArray = new NumArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics