1
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?

要素の挿入 spliceの使い方

Posted at

今回挑戦したのは【指定位置に要素を挿入する】という、配列操作の基本中の基本!


🎯問題概要

  • 1行目で「N, M, K」が与えられる(配列の長さ、挿入位置、挿入したい値)

  • 2行目にN個の整数が並ぶ配列が与えられる

  • この配列の「M番目」に「K」を挿入し、1要素ずつ改行で出力せよ


入力例:

5 3 10
1 2 3 4 5

出力例:

1
2
10
3
4
5



🛠️解き方

配列に挿入するには splice() を使うのがベスト!

配列.splice(挿入位置index, 削除数, 挿入したい値);

今回は M 番目に K を入れたいので、インデックスは M-1、削除はなしで 0 にする。


✅OKコード例

const rl = require('readline').createInterface({ input: process.stdin });
const lines = [];

rl.on('line', (input) => {
    lines.push(input);
});

rl.on('close', () => {
    const [N, M, K] = lines[0].split(' ').map(Number);
    const arr = lines[1].split(' ').map(Number);

    // M番目(インデックスM-1)にKを挿入
    arr.splice(M - 1, 0, K);

    // 各要素を改行区切りで出力
    arr.forEach(num => console.log(num));
});



気づきメモ

  • splice0 から始まるインデックスを意識しないとズレる。
  • pushunshift では位置を指定できないのでこの問題には向かない。
  • splice は「挿入・削除・置換」何でもできる!

🆕新しく学んだこと:spliceの用法まとめ

スクリーンショット 2025-05-18 091158.png

⚠注意:spliceは元の配列を直接変更します!(非破壊じゃない)




僕の失敗談(´;ω;`)と解決法🐈

1
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
1
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?