keep learning, keep coding!
Problem - 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
.
翻譯蒟蒻
計算 nums 陣列中每個元素從第一個元素開始到當前元素的和,並將這些和作為新的陣列返回。
Example 1:
1
2
3Input: 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:
1
2
3Input: 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:
1
2Input: nums = [3,1,2,10,1]
Output: [3,4,6,16,17]
Solution - JavaScript
Solution 1:
藉由建立一個新的陣列來儲存加總後的結果。
1 | /** |
Solution 2:
加總之後直接改變陣列的值,作為新的陣列輸出。
1 | /** |
Solution - Ruby
Solution 1:
先設定 sum 初始值為 0,透過 map
方法累加成為新的陣列。
1 | def running_sum(nums) |
Solution 2:
使用 map
與 with_index
,計算索引 0 到當前索引 index 的所有數字的總和。
1 | def running_sum(nums) |
Solution - PHP
Solution 1:
1 | function runningSum($nums) { |
Solution 2:
1 | function runningSum($nums) { |