leetcode(77).303. Range Sum Query - Immutable

来源:互联网 发布:《算法统宗》甲牵一只 编辑:程序博客网 时间:2024/05/20 21:46
题意:

调用方法,统计角标i,j之间的数组值的和。

初步分析:

创建sum数组,存储前n个元素的和

public class NumArray {    int[] sums;    public NumArray(int[] nums) {        int sum = 0;        this.sums = new int[nums.length];        for(int i=0;i<nums.length;i++){            sum += nums[i];            sums[i]=sum;        }    }    public int sumRange(int i, int j) {        return i==0 ? sums[j]:sums[j]-sums[i-1];    }}// Your NumArray object will be instantiated and called as such:// NumArray numArray = new NumArray(nums);// numArray.sumRange(0, 1);// numArray.sumRange(1, 2);


0 0
原创粉丝点击