Skip to content

Commit cf3e83c

Browse files
committed
Create range-sum-query-immutable.py
1 parent 13ac063 commit cf3e83c

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Time: ctor: O(n),
2+
# lookup: O(1)
3+
# Space: O(n)
4+
#
5+
#Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
6+
#
7+
# Example:
8+
# Given nums = [-2, 0, 3, -5, 2, -1]
9+
#
10+
# sumRange(0, 2) -> 1
11+
# sumRange(2, 5) -> -1
12+
# sumRange(0, 5) -> -3
13+
# Note:
14+
# You may assume that the array does not change.
15+
# There are many calls to sumRange function.
16+
#
17+
18+
class NumArray(object):
19+
def __init__(self, nums):
20+
"""
21+
initialize your data structure here.
22+
:type nums: List[int]
23+
"""
24+
self.accu = [0]
25+
for num in nums:
26+
self.accu += self.accu[-1] + num,
27+
28+
def sumRange(self, i, j):
29+
"""
30+
sum of elements nums[i..j], inclusive.
31+
:type i: int
32+
:type j: int
33+
:rtype: int
34+
"""
35+
return self.accu[j + 1] - self.accu[i]
36+
37+
38+
# Your NumArray object will be instantiated and called as such:
39+
# numArray = NumArray(nums)
40+
# numArray.sumRange(0, 1)
41+
# numArray.sumRange(1, 2)

0 commit comments

Comments
 (0)