leetcode和算法----日更

leetcode 303 区域和检索-数组不可变

2020-02-21  本文已影响0人  Arsenal4ever

如果直接提交,会超时,因为和是多次调用。(生成)加一层缓存,用的 append 的方法,代码不如在前面添加 0(防御式编程思想)简洁。

直接加缓存。

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.numsCache = []
        numsSum = 0
        for idx in range(len(nums)):
            numsSum += nums[idx]
            self.numsCache.append(numsSum)

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        if i > 0:
            return self.numsCache[j] - self.numsCache[i-1]
        else:
            return self.numsCache[j]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

防御式:

class NumArray(object):

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

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        return self.numsCache[j+1] - self.numsCache[i] 
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)
上一篇 下一篇

猜你喜欢

热点阅读