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?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 線形探索メニュー応用編 JavaScript 部分数列

Last updated at Posted at 2022-10-31

部分数列 (paizaランク C 相当)

解答例(for,if)

forとifで解きます。答えはansとします。iが一つも存在しなかったら-1なので、初期値-1とします。
aの部分数列がbになっているか、aの先頭から順に調べます。
一番小さいiが見つかったら、そこで線形探索を終わります。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

const [n, m] = lines[0].split(" ").map(Number);
const a = lines[1].split(" ").map(Number);
const b = lines[2].split(" ").map(Number);

//bがaの部分数列か調べる
let ans = -1;// i がひとつも存在しない場合は -1

for (let i = 0; i <= n - m; i++) {
  let flag = true;//条件を満たすbが存在したらtrue
  for (let j = 0; j < m; j++) {
    if (a[i + j] !== b[j]) { //条件を満たさなかったら次へ
      flag = false;//満たさない
      break;//次へ
    }
  }
  //条件を満たしたらbreak、一番小さいiを求めるので
  if (flag) {
    ans = i + 1;//一番小さいi
    break;//一番小さいiが求まったので終わり 
  }
}
console.log(ans);
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?