LoginSignup
0
0

More than 1 year has passed since last update.

Leetcode 解いてみた 1480. Running Sum of 1d Array

Last updated at Posted at 2022-10-07
  1. Running Sum of 1d Array
    Rubyを勉強中なのでRubyで解きました。

問題
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.

例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].

例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].

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

制約
1 <= nums.length <= 1000
-10^6 <= nums[i] <= 10^6

【解いた】
要するに、アウトプットするべき配列の要素はインプットの数字のこれまでの数全てを合計したものを配列の1要素にしてますよね。
例) output[3] = nums[0] + nums[1] + nums[2] + nums[3]

これをfor文を用いて解くとこうなりました。

def running_sum(nums)
    output=[]
    i=0
    for i in 0..nums.length-1 do
        output[i]= output[i-1].to_i + nums[i].to_i
    end
    return output
end

結果は・・・

スクリーンショット 2022-10-07 13.32.36.png

OK!

何かの参考になれば幸いです。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0