Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.php
Example:ios
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.
複製代碼
根據題意,設置一個 sums 數組,長度爲 len(nums)+1 ,索引 n 對應的值即爲前 n 個數字之和,最後根據 i 和 j ,利用 sums 數組,sums[j+1]-sums[i] 便可得出結果,時間複雜度爲 O(1),空間複雜度爲 O(N)。微信
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.sums = [0]*(len(nums)+1)
for i in range(len(nums)):
self.sums[i+1] = self.sums[i] + nums[i]
print(self.sums)
def sumRange(self, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return self.sums[j+1]-self.sums[i]
複製代碼
Runtime: 60 ms, faster than 96.35% of Python online submissions for Counting Bits.
Memory Usage: 15.7 MB, less than 16.54% of Python online submissions for Counting Bits.
複製代碼
每日格言:經常是最終一把鑰匙打開了門。less