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 法一:暴力
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 };
原文地址:https://www.cnblogs.com/zle1992/p/10466479.html
时间: 2024-10-12 01:28:55