LeetCode——区域和检索
题目描述:
给定一个整数数组 nums,求出数组从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点。
实现 NumArray 类:
NumArray(int[] nums) 使用数组 nums 初始化对象
int sumRange(int i, int j) 返回数组 nums 从索引 i 到 j(i ≤ j)范围内元素的总和,包含 i、j 两点(也就是 sum(nums[i], nums[i + 1], … , nums[j]))
示例:
输入:
[“NumArray”, “sumRange”, “sumRange”, “sumRange”]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
输出:
[null, 1, -1, -3]
解释:
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return 1 ((-2) + 0 + 3)
numArray.sumRange(2, 5); // return -1 (3 + (-5) + 2 + (-1))
numArray.sumRange(0, 5); // return -3 ((-2) + 0 + 3 + (-5) + 2 + (-1))
提示:
0 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= i <= j < nums.length
最多调用 104 次 sumRange 方法
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-query-immutable
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
解法一:
直接在sumRange函数中遍历nums数组,一个个加过去,返回最终的搜索结果。
解法二:
我们在init函数中再定义一个sums数组,每个位置对应于nums每个位置,用来存储前面所有nums中的数之和,即self.sums[i] =self.sums[i - 1] + self.nums[i]
然后我们在sumRange函数中计算left到right的和:即self.sums[right] - self.sums[left - 1],要注意:当left等于0的时候,从0到right的和就是sums[right]
解法一python代码:
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
def sumRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: int
"""
sum = 0
for i in range(left, right + 1):
sum += self.nums[i]
return sum
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
解法二python代码:
class NumArray(object):
def __init__(self, nums):
"""
:type nums: List[int]
"""
self.nums = nums
self.sums = [self.nums[0]]
for i in range(1, len(nums)):
self.sums.append(self.sums[i - 1] + self.nums[i])
def sumRange(self, left, right):
"""
:type left: int
:type right: int
:rtype: int
"""
if left == 0:
return self.sums[right]
return self.sums[right] - self.sums[left - 1]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)