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) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
My code:
class NumArray(object):
def __init__(self, nums):
"""
initialize your data structure here.
:type nums: List[int]
"""
self.nums = nums
self.sums = [0 for i in range(len(nums))]
for index in range(len(nums)):
if index == 0:
self.sums[index] = self.nums[index]
else:
self.sums[index]= self.sums[index-1]+self.nums[index]
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
:type i: int
:type j: int
:rtype: int
"""
if i<0 or j<0 or i>len(self.nums) or j>len(self.nums) or i>j:
return 0
elif i==0:
return self.sums[j]
else:
return self.sums[j]-self.sums[i-1]
public class NumArray {
int[] sums;
public NumArray(int[] nums) {
for(int i=1;i<nums.length;i++){
nums[i]=nums[i-1]+nums[i];
}
this.sums=nums;
}
public int sumRange(int i, int j) {
if(i==0) return this.sums[j];
else return this.sums[j]-this.sums[i-1];
}
}
/**
* Your NumArray object will be instantiated and called as such:
* NumArray obj = new NumArray(nums);
* int param_1 = obj.sumRange(i,j);
*/