LeetCode1480[一维数组的动态和]
题目:
链接:
详情:
实例:
实例1:
实例2:
实例3:
提示:
题解:
输出项的每一项都为输入项的累计和
设输出out
设输入in
out[0] = in[0]
out[1] = in[0] + in[1]
out[2] = in[0] + in[1] + in[2] = out[1] + in[2]
out[3] = in[0] + in[1] + in[2] + in[3] = out[2] + in[3]
out[4] = in[0] + in[1] + in[2] + in[3] + in[4] = out[3] + in[4]
...
以此类推
out[n] = out[n - 1] + in[n]
最后形成代码如下:
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> iRetVec;
long long sum = 0;
for (int i = 1; i < nums.size(); i++)
nums.at(i) += nums.at(i - 1);
return nums;
}
};
本文来自博客园,作者:EricsT,转载请注明原文链接:https://www.cnblogs.com/EricsT/p/18526172