303. Range Sum Query

一、题目

  1、审题 

  

  2、分析

    给出一个整形数组,返回从下标 i 到 j 的元素之和。

二、解答

  1、思路

    ①、新建一个数组,如下标 i : 存储下标 0 ~ i 的元素之和。

    ②、最终返回 nums[j] - nums[i];

class NumArray {

    private int[] nums;
    
    public NumArray(int[] nums) {
        for (int i = 1; i < nums.length; i++) 
            nums[i] += nums[i-1];
        
        this.nums = nums;
    }
    
    public int sumRange(int i, int j) {
        if(i == 0)
            return nums[j];
        
        return nums[j] - nums[i - 1];
    }
}
原文地址:https://www.cnblogs.com/skillking/p/10033084.html