// 前缀和数组preSum[]:preSum[i]记录nums[0,i-1]区间的累加和 class ex_preSum{ private: vector<int> preSum; public: ex_preSum(vector<int> nums){ preSum.resize(nums.size()+1); // 原数组下标[0,n-1]。preSum数组下标[0,n],其中preSum[0]=0,从preSum[1]开始。 // preSum[i] = preSum[i-1]+nums[i-1]; preSum[0] = 0; for(int i=1;i<preSum.size();i++){ // nums[i-1]的原因:因为此处这个i是preSum的下标,而preSum的下标=nums的位序,要取nums第i个元素值时就要通过nums[i-1]取 preSum[i] = preSum[i-1]+nums[i-1]; } } int deal(int startIdx,int endIdx){ int t = preSum[endIdx+1] - preSum[startIdx]; return t; } bool test_deal(){ vector<int> nums{0,1,2,3,4,5}; return ex_preSum(nums).deal(3,5) == 12; } };
标签:前缀,nums,vector,ex,数组,preSum From: https://www.cnblogs.com/jinziguang/p/18223147