Leetcode - Range Sum Query - Immutable

Screenshot from 2016-02-27 21:06:26.png

My code:

public class NumArray {
    private int[] sums;
    private int[] nums;
    public NumArray(int[] nums) {
        this.nums = nums;
        this.sums = new int[nums.length];
        for (int i = 0; i < nums.length; i++)
            sums[i] = nums[i];
        for (int i = 1; i < sums.length; i++)
            sums[i] += sums[i - 1];
    }

    public int sumRange(int i, int j) {
        if (i < 0 || i >= sums.length)
            return 0;
        else if (j < 0 || j >= sums.length)
            return 0;
        return nums[i] + sums[j] - sums[i];
    }
}


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

同一个思路。
Anyway, Good luck, Richardo!

My code:

public class NumArray {

    public NumArray(int[] nums) {
        
    }

    public int sumRange(int i, int j) {
        
    }
}


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

简单题,没什么好说的。

Anyway, Good luck, Richardo! -- 08/20/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容