l203 range sum query immutable

题目描述

1
2
3
4
5
6
7
8
9
10
11
12

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.

解题思路

  • 针对每次输入都计算直接使用sum 无需额外空间
  • 计算sum值,根据index输入输出 需要空间

Python实现1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class (object):

def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums

def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return sum(self.nums[i:j+1])

Runtime: 959 ms

Python实现2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class (object):

def __init__(self, nums):
"""
:type nums: List[int]
"""
self.sums =[]
s = 0
for n in nums:
s+=n
self.sums.append(s)
print self.sums
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
if i==0:
return self.sums[j]
else:
return self.sums[j]-self.sums[i-1]

Runtime: 109 ms

Python实现3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class (object):

def __init__(self, nums):
"""
:type nums: List[int]
"""
self.sums = [0]*(len(nums)+1)
for i in xrange(1,len(nums)+1):
self.sums[i] = self.sums[i-1]+nums[i-1]

def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.sums[j+1]-self.sums[i]

Runtime: 62ms