303. Range Sum Query - Immutable(前缀和)
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
class NumArray { public: vector<int> dp; NumArray(vector<int>& nums) { dp = vector<int>(nums.size()+1,0); for(int i = 1; i <= nums.size();i++) { dp[i]= dp[i-1] + nums[i-1]; } } int sumRange(int left, int right) { return dp[right+1] - dp[left]; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(left,right); */
法一:暴力
1 class NumArray { 2 3 public: 4 vector<int> Nums; 5 6 NumArray(vector<int> nums) { 7 Nums =nums; 8 } 9 10 int sumRange(int i, int j) { 11 int res = 0; 12 for(int k = i;k<=j;k++) 13 res+=Nums[k]; 14 return res; 15 } 16 };
法二:
sumRange(i,j)=sum[j+1]−sum[i]
1 class NumArray { 2 3 public: 4 vector<int> Nums; 5 vector<int> Sums; 6 7 8 NumArray(vector<int> nums) { 9 Nums =nums; 10 Sums = vector<int>(nums.size()+1,0); 11 for(int i = 0;i<nums.size();i++) 12 Sums[i+1]=Sums[i]+nums[i]; 13 } 14 15 int sumRange(int i, int j) { 16 int res = 0; 17 res = Sums[j+1]-Sums[i]; 18 return res; 19 } 20 };