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

hashmapの使い方

Posted at

タイトルの通り

https://atcoder.jp/contests/abc231/tasks/abc231_b
に相当躓いた。
解いた人のソースを見てみるとどうやらhashmapを使えば簡単に書けるらしい。
しかしながらhashmapってなんぞや状態なので調べてみた
https://moshg.github.io/rust-std-ja/std/collections/struct.HashMap.html#method.entry
公式の解説だけどよくわからん
https://ja.wikipedia.org/wiki/%E3%83%8F%E3%83%83%E3%82%B7%E3%83%A5%E3%83%86%E3%83%BC%E3%83%96%E3%83%AB
を見てみるとどうやら配列の添え字に文字列を使えるようにした構造らしい。
今回のやつを使うのには確かに便利。
というわけで頭を動かしがてら自分で書いてみた
サンプルみているとentryとor_insertでいけそう.
あとはイテレータになるみたいなのでmaxとって終わりか。
hashmapの要素はタプルと同じ感じで取り出せそうなのでそれをうまいこと使う。

test.rs
let mut map: HashMap<&str, u32> = HashMap::new();
map.entry("poneyland").or_insert(12);
map.entry("poneyla").or_insert(2);

println!("{:?}",map.iter());

を実行したときが
[("poneyland", 12), ("poneyla", 2)]
になる。

というわけで解答。

test.rs
use proconio::input;
use std::collections::{HashMap, HashSet};

fn main() {
  input! {
    n: usize,
    mut S: [String; n]
}

let mut map = HashMap::new();
for i in S{
*map.entry(i).or_insert(0) +=1;
}

let ans = map.iter().max_by_key(|x| x.1).unwrap();

  println!("{}",ans.0);
}

参考にした人の解答とほぼ同じ。
精進したいねえ

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?