0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

1480. Running Sum of 1d Array - Day 1

Posted at

問題

Screenshot 2025-02-15 at 14.52.38.png

解答コード

main.rs
impl Solution {
    pub fn running_sum(nums: Vec<i32>) -> Vec<i32> {
        let mut vec: Vec<i32> = vec![nums[0]];

        for i in 1..nums.len() {
            vec.push(vec[i-1] + nums[i])
        }

        vec
    }
}

解説

Rustでベクタを使用して、解答を導きました。

  1. mut演算子をつけて変数vet可変にし、且つnumsの最初の要素で初期化しています
  2. forループはnumsの要素の1つ目からnums.len()までのインデックスまでを繰り返し、現在のnumsの累積和を計算し、vecに追加します

初めは初期化をした後、存在し得ないvecの0個目の要素にアクセスしていたので怒られていましたね〜。

main.rs
// Bad! Because complipe Error!
// Line 4: Char 12: index out of bounds:
// the len is 0 but the index is 0 
impl Solution {
    pub fn running_sum(nums: Vec<i32>) -> Vec<i32> {
        let mut vec: Vec<i32> = Vec::new();
        vec[0] = nums[1];

        for i in 1..nums.len() {
            vec[i] = vec[i] + nums[i - 1];
        }
        vec
    }
}
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?