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.
给一个整数数组,找出两个index之间的数字和。
如果每次遍历i, j之间的数字相加求和,十分的不高效,无法通过OJ。
解法:DP,建一个数组dp,其中dp[i]表示[0, i]区间的数字之和,那么[i,j]就可以表示为dp[j]-dp[i-1],当i=0时,直接返回dp[j]即可。
Java:
class NumArray { int[] nums; public NumArray(int[] nums) { for(int i = 1; i < nums.length; i++) nums[i] += nums[i - 1]; this.nums = nums; } public int sumRange(int i, int j) { if(i == 0) return nums[j]; return nums[j] - nums[i - 1]; } }
Python:
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.accu = [0] for num in nums: self.accu += self.accu[-1] + num, def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ return self.accu[j + 1] - self.accu[i]
Python:
# Time: ctor: O(n), # lookup: O(1) # Space: O(n) class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.accu = [0] for num in nums: self.accu.append(self.accu[-1] + num), def sumRange(self, i, j): """ sum of elements nums[i..j], inclusive. :type i: int :type j: int :rtype: int """ return self.accu[j + 1] - self.accu[i]
Python: wo
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ s, n = 0, len(nums) self.dp = [0] * (n + 1) for i in xrange(n): s += nums[i] self.dp[i + 1] = s def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return self.dp[j + 1] - self.dp[i]
C++:
class NumArray { public: NumArray(vector<int> &nums) { accu.push_back(0); for (int num : nums) accu.push_back(accu.back() + num); } int sumRange(int i, int j) { return accu[j + 1] - accu[i]; } private: vector<int> accu; };
C++:
class NumArray { public: NumArray(vector<int> &nums) { dp.resize(nums.size() + 1, 0); for (int i = 1; i <= nums.size(); ++i) { dp[i] = dp[i - 1] + nums[i - 1]; } } int sumRange(int i, int j) { return dp[j + 1] - dp[i]; } private: vector<int> dp; };
C++:
class NumArray { public: NumArray(vector<int> &nums) { dp = nums; for (int i = 1; i < nums.size(); ++i) { dp[i] += dp[i - 1]; } } int sumRange(int i, int j) { return i == 0? dp[j] : dp[j] - dp[i - 1]; } private: vector<int> dp; };
类似题目:
[LeetCode] 304. Range Sum Query 2D - Immutable 二维区域和检索 - 不可变Range Sum Query - Mutable
Range Sum Query 2D - Mutable