[LeetCode刷題筆記] 1480 – Running Sum of 1d Array
題目描述:
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:
Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
Example 2:
Input: nums = [1,1,1,1,1]
Output: [1,2,3,4,5]
Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
Example 3:
Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Constraints:
1 <= nums.length <= 1000-10^6 <= nums[i] <= 10^6
一刷題解(Brute Force):
這題要我們遍歷一邊遍歷數組,一邊把數組當前元素及其前一個元素累積起來。累積後的值有兩個用途,一是置於新數組中,最後把這個數組返回;二是提供給下一個元素,並繼續累積,得出新的元素。直到遍歷結束,因此返回數組的最後一個元素應等於原始數組所有元素的和,第一個元素則與原始數組的首位元素相等。
解法也很簡單。由於結果數組的0號元素 = 原始數組的0號元素,因此先使 result[0] = nums[0];。然後再從1號元素開始遍歷nums,每次循環得出當前元素與前面元素的累積值的和(prevSum + nums[i]),然後再把該元素賦值給result[i]即可。
public class Solution {
public int[] RunningSum(int[] nums) {
int[] result = new int[nums.Length];
int prevSum = nums[0];
result[0] = prevSum;
for (int i = 1; i < nums.Length; i++)
{
prevSum += nums[i];
result[i] = prevSum;
}
return result;
}
}