JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Implement the NumArray class:

NumArray(int[] nums) Initializes the object with the integer array nums. int sumRange(int i, int j) Return the sum of the elements of the nums array in the range [i, j] inclusive (i.e., sum(nums[i], nums[i + 1], … , nums[j]))

Example 1:

Input
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]

Explanation

NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))

Code

class NumArray {
    List<Integer> sum = new ArrayList<>();
    public NumArray(int[] nums) {
        sum.add(0);
        int acc = 0;
        for (int i = 0; i < nums.length; i++) {
            acc += nums[i];
            sum.add(acc);
        }
    }

    public int sumRange(int i, int j) {
        return sum.get(j + 1) - sum.get(i);
    }
}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */
class NumArray:

    def __init__(self, nums: List[int]):
        sum = [0]
        acc = 0
        for i in range(len(nums)):
            acc += nums[i]
            sum.append(acc)
        self.sum = sum

    def sumRange(self, i: int, j: int) -> int:
        return self.sum[j + 1] - self.sum[i]


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)