给你一个数组nums
,请你完成两类查询,其中一类查询要求更新数组下标对应的值,另一类查询要求返回数组中某个范围内元素的总和。
实现NumArray
类:
NumArray(int[] nums)
用整数数组nums
初始化对象void update(int index, int val)
将nums[index]
的值更新为val
int sumRange(int left, int right)
返回子数组nums[left, right]
的总和(即,nums[left] + nums[left + 1], ..., nums[right])
示例:
输入:
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
输出:
[null, 9, null, 8]
解释:
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // 返回 9 ,sum([1,3,5]) = 9
numArray.update(1, 2); // nums = [1,2,5]
numArray.sumRange(0, 2); // 返回 8 ,sum([1,2,5]) = 8
提示:
1 <= nums.length <= 3 * 10^4
-100 <= nums[i] <= 100
0 <= index < nums.length
-100 <= val <= 100
0 <= left <= right < nums.length
- 最多调用
3 * 10^4
次update
和sumRange
方法
1.暴力超时
Python解答:
class NumArray:
def __init__(self, nums: List[int]):
self.arr = nums
def update(self, index: int, val: int) -> None:
self.arr[index] = val
def sumRange(self, left: int, right: int) -> int:
total = 0
for i in range(left, right+1):
total += self.arr[i]
return total
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(index,val)
# param_2 = obj.sumRange(left,right)
留言