Files
hello-algo/ja/codes/rust/chapter_searching/hashing_search.rs
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

51 lines
1.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* File: hashing_search.rs
* Created Time: 2023-07-09
* Author: codingonion (coderonion@gmail.com)
*/
use hello_algo_rust::include::ListNode;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
/* ハッシュ探索(配列) */
fn hashing_search_array<'a>(map: &'a HashMap<i32, usize>, target: i32) -> Option<&'a usize> {
// ハッシュテーブルの key:目的の要素、value:インデックス
// ハッシュテーブルにこの key が存在しない場合、None を返す
map.get(&target)
}
/* ハッシュ探索(連結リスト) */
fn hashing_search_linked_list(
map: &HashMap<i32, Rc<RefCell<ListNode<i32>>>>,
target: i32,
) -> Option<&Rc<RefCell<ListNode<i32>>>> {
// ハッシュテーブルの key:目的のノードの値、value:ノードオブジェクト
// ハッシュテーブルにこの key が存在しない場合、None を返す
map.get(&target)
}
/* 実行用コード */
pub fn main() {
let target = 3;
/* ハッシュ探索(配列) */
let nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
// ハッシュテーブルを初期化する
let mut map = HashMap::new();
for (i, num) in nums.iter().enumerate() {
map.insert(*num, i); // key:要素、value:インデックス
}
let index = hashing_search_array(&map, target);
println!("目的の要素 3 のインデックス = {}", index.unwrap());
/* ハッシュ探索(連結リスト) */
let head = ListNode::arr_to_linked_list(&nums);
// ハッシュテーブルを初期化する
// let mut map1 = HashMap::new();
let map1 = ListNode::linked_list_to_hashmap(head);
let node = hashing_search_linked_list(&map1, target);
println!("目的のノードの値 3 に対応するノードオブジェクトは {:?}", node);
}