leetcode 303. Range Sum Query - Immutable ( Python )

描述

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

請做者吃包子
支付寶

支付寶

微信

微信
相關文章
相關標籤/搜索