Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
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.
题目大意:给定一个数组,返回小标[i, j]的元素之和。
用途:在窗口一定大小时,做滑动平均。可用于图像中的均值滤波
思路一:每次给定[i, j],直接计算。
1 class NumArray { 2 private: 3 vector<int> sum; 4 public: 5 NumArray(vector<int>& nums) { 6 sum = nums; 7 } 8 9 int sumRange(int i, int j) { 10 int ans = 0; 11 for (int k = i; k <= j; ++k) { 12 ans += sum[k]; 13 } 14 return ans; 15 } 16 };
思路二:
sum[k] 记录 [0,k]的累加和,计算下标[i, j]的元素和为sum[j] - sum[i - 1], k = 0时,sum[0] = nums[0];
1 class NumArray { 2 private: 3 vector<int> sum; 4 public: 5 NumArray(vector<int>& nums) { 6 sum.assign(nums.begin(), nums.end()); 7 for (int i = 1; i < nums.size(); ++i) { 8 sum[i] = sum[i - 1] + nums[i]; 9 } 10 } 11 12 int sumRange(int i, int j) { 13 if (i == 0) return sum[j]; 14 return sum[j] - sum[i - 1]; 15 } 16 };
python3:
1 class NumArray: 2 def __init__(self, nums: List[int]): 3 self.lists = [] #定义实例变量 4 for i, v in enumerate(nums): 5 if i == 0: 6 self.lists.append(v) 7 else: 8 self.lists.append(self.lists[-1] + v) 9 10 def sumRange(self, i: int, j: int) -> int: 11 if i == 0: 12 return self.lists[j] 13 return self.lists[j] - self.lists[i - 1]
class NumArray: def __init__(self, nums: List[int]): self.lists = [] for i, v in enumerate(nums): if i == 0: self.lists.append(v) else: self.lists.append(self.lists[i-1] + v)
def sumRange(self, i: int, j: int) -> int: if i == 0: return self.lists[j] return self.lists[j] - self.lists[i - 1]