美文网首页
LeetCode-303 区域和检索 - 数组不可变

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

作者: FlyCharles | 来源:发表于2019-02-24 01:26 被阅读0次

1. 题目

https://leetcode-cn.com/problems/range-sum-query-immutable/submissions/

给定一个整数数组 nums,求出数组从索引 ij (i ≤ j) 范围内元素的总和,包含 i, j 两点。

示例:

给定 nums = [-2, 0, 3, -5, 2, -1],求和函数为 sumRange()

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

说明:

  1. 你可以假设数组不可变
  2. 会多次调用 sumRange 方法

2. 我的AC

方法一

class NumArray(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])   


# 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.nums = nums
        self.sums = []
        temp_sum = 0
        for num in nums:
            temp_sum += num
            self.sums.append(temp_sum)
            
    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]

3. 小结

  1. 出错点:注意索引 i == 0,列表的索引特别要注意是正是负

相关文章

网友评论

      本文标题:LeetCode-303 区域和检索 - 数组不可变

      本文链接:https://www.haomeiwen.com/subject/ngtmyqtx.html