Range Sum Query - Immutable

来源:互联网 发布:为什么胡歌没女友 知乎 编辑:程序博客网 时间:2024/06/04 23:28

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) -> 1sumRange(2, 5) -> -1sumRange(0, 5) -> -3

Note:

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

这道题要求区间内的和。可以想到,用一个数组保存前n项的和,然后用大的区间减去小的区间就得到中间的那个区间的和。

注意下这个sum数组的长度为n+1, sum[0] = 0,表示当前下标前的和为多少。对应计算差值的时候, 举个例子就能知道下标该如何写了。

例子:

nums =  [1, 2, 3, 4]

sums=   [0, 1, 3, 6, 10]

例如计算:sumRange(0, 2): sums[2+1] - sum[0] = 6

代码:

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



0 0