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?

今回は paiza の「2 つのキュー」の問題に挑戦!


🟦 問題概要

🔹 テーマ

  • 2つのキューを同時に管理する
  • クエリに応じてそれぞれ操作

🔹 やること

  • キューを2つ用意する
  • Q個のクエリを順に処理
  • クエリの種類によって処理・出力を変える

🔹 クエリの種類

1 K X(PUSH)

  • K番目のキューに X を追加
  • 出力なし

2 K(POP)

  • K番目のキューの先頭を削除
  • 削除する前に、キューの先頭の値を出力

3(SIZE)

  • 1番目と2番目のキューの要素数を出力
  • S1 S2 の形式



入力例:

6
1 1 2
1 2 3
1 1 4
3
2 1
3

出力例:

2 1
2
1 1






✅OK例:

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

const lines = [];
rl.on('line', line => lines.push(line));

rl.on('close', () => {
    const Q = Number(lines[0]);
    const query = lines.slice(1).map(q => q.split(' ').map(Number));
    
    const queue = Array.from({ length: 2 }, () => []);
    
    for (let i = 0; i < Q; i++) {
        const [num, k, x] = query[i];
        
        if (num === 1) {
            queue[k-1].push(x);
        } 
        else if (num === 2) {
            console.log(queue[k-1][0]);
            queue[k-1].shift();
        } 
        else {
            console.log(queue[0].length, queue[1].length);
        }
    }
});

🟦 コードの流れ

  • 入力を受け取る
  • Qを取得
  • クエリを数値配列に変換
  • キューを 2 つ作る
  • Q回ループ
    • num === 1push
    • num === 2 → 先頭を出力して shift
    • num === 3 → それぞれの length を出力






📝まとめ

queue1 = [], queue2 = [] と書いてもいいが、 queue = [ [], [] ] と二次元配列でキューを管理。

あとは、前回同様にFIFOを実装するのと、新しいSIZEについては.lengthで配列の長さを出力するだけ。

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?