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?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 ソートメニュー応用編 JavaScript Top - k (hard)

Last updated at Posted at 2022-09-23

Top - k (hard) (paizaランク C 相当)

JavaScriptで解いてみました。
a の k_i 番目に大きい値を、その都度、数列aの中から探していると時間がかかります。
先に数列aを大きい順に並べ替えると、a の k_i 番目に大きい値はa[k_i - 1]で、一発で求まります。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
//数列の長さを表す整数 n, q 
const [n, q] = lines[0].split(" ").map(Number);
//数列 a
const a = lines[1].split(" ").map(Number);
//数列 k
const k = lines[2].split(" ").map(Number);

//aを降順にソート
a.sort((a, b) => b - a);

//1 以上 q 以下の各 i について、 
for (let i = 0; i < q; i++) {
    //a の k_i 番目に大きい値をそれぞれ求め、改行区切りで出力
    console.log(a[k[i] - 1]);
}
1
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
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?