2
1

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 3 years have passed since last update.

rustと2分探索の使い方

Last updated at Posted at 2021-12-11

初めに

2分探索をデフォルトの binary_search(スライスのメソッド)で書いてみたというだけ。
公式の
https://moshg.github.io/rust-std-ja/std/primitive.slice.html#method.binary_search
を見ればいいだけなんだけどメモ代わり。
あと2分探索法の概要は知ってるけど自分で実装するの面倒な人向け

今回の使い方

2*10^5個のベクタ要素に整数が入ってる。ある値より大きい整数が何個あるか数える
ベクタの要素数が分かっているのでソートして指定した値と最も近い要素の位置がわかればよい。
なお、Sが整数が入っているベクタ、ある値が入っているベクタがX。

main.rs
mut S: [usize; n],
mut X: [usize; q]

S.sort();

let len = S.len();
let mut count = Ok(10);
let mut t_count = 0;
for i in X{

  count = S.binary_search(&i);
  if count.is_ok(){
    t_count = count.unwrap();
  }else{
    t_count = count.unwrap_err();
  }

  println!("{:?}",t_count);
}

binary_searchはresult型なので中の値を引っ張ってくるために
unwrap()する必要あるが、OkとErrでやり方が違うので分けた。

ぴったりの値があるときはOkと一緒にその要素の位置、
無い時は最初の自分より大きい数字の位置を出す。この辺は公式見ればいいので省略。Sの要素数より大きい値を返すのは少し要注意かも・・・
今更だけどmatchでかけばよかった。
あと同一要素がある場合はスライスになるので注意しなきゃだけどどうすりゃいいかなあ・・・

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?