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?

商品検索はMap派?配列派?

Posted at

Paizaの「商品検索」での気づきメモです。Mapばっか使ってたら、配列で .has()を使ってミスった…。
あと、以前にコメントで教えていたただいたindexOfを使ってみたよ!


🔍 問題概要(Paiza: 辞書に登録済みか判定)

問題URL: https://paiza.jp/works/mondai/data_structure/data_structure__dict_boss

  • N個の商品名と、Q個の検索したい商品名が与えられる。
  • 「最初に出てきたインデックス」を出力。
  • 該当商品がなければ -1


入力例:

3 2
a
b
c
b
d

出力例:

2
-1


❌ NG例:配列にhas()使ってしまった

if (goodsArray.has(item)) {
    // TypeError: goodsArray.has is not a function
}

配列には .has()使えない!
SetMap にだけ使えるやつ。配列なら .includes() が正解。


✅ OK例①:配列 + includes + indexOf

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

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

rl.on('close', () => {
    const [N, Q] = lines[0].split(' ').map(Number);
    const goodsArray = lines.slice(1, N + 1);
    const queries = lines.slice(N + 1);

    queries.forEach(item => {
        if (goodsArray.includes(item)) {
            console.log(goodsArray.indexOf(item) + 1); // 1始まりに注意!
        } else {
            console.log("-1");
        }
    });
});
  • .includes() で存在確認
  • .indexOf() でインデックス取得(0始まりなので +1


✅ OK例②:Mapで高速検索(O(1))

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

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

rl.on('close', () => {
    const [N, Q] = lines[0].split(' ').map(Number);
    const goodsArray = lines.slice(1, N + 1);
    const queries = lines.slice(N + 1);

    const goodsMap = new Map();
    goodsArray.forEach((item, index) => {
        if (!goodsMap.has(item)) {
            goodsMap.set(item, index + 1); // 1始まりで記録
        }
    });

    const results = queries.map(item =>
        goodsMap.has(item) ? goodsMap.get(item) : -1
    );

    console.log(results.join('\n'));
});
  • Mapで商品名 → 最初の出現位置 を記録
  • 検索は .has().get() の組み合わせ


✅ 技術的まとめ

  • 配列: .includes() / .indexOf()

  • Map: .has() / .get()

  • 出力が1始まりなら +1 を忘れずに

  • 検索が多い or 高速化したいなら Map を使う

最近はhas()ばっかり使ってたから、癖でやっちゃった(´;ω;`)



僕の失敗談(´;ω;`)と解決話🚀

0
0
2

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?