2020-02-15
303. 区域和检索 - 数组不可变 E
给定一个整数数组 nums,求出数组从索引 i 到 j (i ≤ j) 范围内元素的总和,包含 i, j 两点。
一维前缀和:
class NumArray { public: vector<long long> dp; NumArray(vector<int>& nums) { int n = nums.size(); dp.resize(n+1); for(int i = 1; i <= n; i++) dp[i] = dp[i-1] + nums[i-1]; } int sumRange(int i, int j) { return dp[j+1]-dp[i]; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray* obj = new NumArray(nums); * int param_1 = obj->sumRange(i,j); */
413. 等差数列划分 M
如果一个数列至少有三个元素,并且任意两个相邻元素之差相同,则称该数列为等差数列。
class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { int n = A.size(); vector<int> dp(n); //dp[i] 表示以A[i]结尾的等差数列数量 for(int i = 2; i < n; i++) if(A[i]-A[i-1] == A[i-1]-A[i-2]) dp[i] = dp[i-1]+1; int sum = 0; for(auto x:dp) sum+=x; return sum; } };