LoginSignup
0
0

More than 1 year has passed since last update.

Leetcode easy: 1480. Running Sum of 1d Array(JavaScript)

Last updated at Posted at 2022-07-09

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:

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

処理の流れをざっくり考える

  • 配列を初期化して乗算の結果を追加していく
  • 前の計算結果を使うようにする

最初に書いたコード

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function(nums) {
    let total_so_far = 0;
    let sum_nums = [];
    for (let i=0; i<nums.length; i++){
        total_so_far += nums[i];
        sum_nums.push(total_so_far);
    }
    return sum_nums;
};

結果

Runtime: 75 ms, faster than 76.20% of JavaScript online submissions for Running Sum of 1d Array.
Memory Usage: 42.3 MB, less than 72.38% of JavaScript online submissions for Running Sum of 1d Array.

調べたこと

Complexityについてよくわかっていないので調べた。
今回はTimeComplexityもSpaceComplexityもとてもシンプルだけど・・・

答えを見て改善したこと

ビデオを見て書き換えてみる。配列を上書きする方法。

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var runningSum = function(nums) {
    for (let i=1; i<nums.length; i++){
        nums[i] += nums[i-1];
    }
    return nums;
};

complexityは変わらないけどとてもシンプルにかけた。

Runtime: 77 ms, faster than 72.91% of JavaScript online submissions for Running Sum of 1d Array.
Memory Usage: 42.6 MB, less than 37.54% of JavaScript online submissions for Running Sum of 1d Array.

0
0
0

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