題目


Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).

Return the running sum of nums.

Example 1:

1Input: nums = [1,2,3,4]
2Output: [1,3,6,10]
3Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

Example 2:

1Input: nums = [1,1,1,1,1]
2Output: [1,2,3,4,5]
3Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].

Example 3:

1Input: nums = [3,1,2,10,1]
2Output: [3,4,6,16,17]

Constraints:

$$ \begin{array}{l} 1 <= nums.length <= 1000 \\ -10^6 <= nums[i] <= 10^6 \end{array} $$

我的思路


第 i 個 runningSum 等於 nums[0] + … + nums[i-1] + nums[i];

而 nums[0] + nums[i-1] 等於 runningSum[i-1];

所以可以得到 runningSum[i] = runningSum[i-1] + nums[i];

程式碼


 1class Solution {
 2    public int[] runningSum(int[] nums) {
 3        int[] runningSum = new int[nums.length];
 4        runningSum[0] = nums[0];
 5        for(int i = 1; i < nums.length; i++) {
 6            runningSum[i] = runningSum[i-1] + nums[i];
 7        }
 8        return runningSum;
 9    }
10}