Files
hello-algo/ja/codes/ruby/chapter_searching/hashing_search.rb
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

48 lines
1.4 KiB
Ruby
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.
=begin
File: hashing_search.rb
Created Time: 2024-04-09
Author: Blue Bean (lonnnnnnner@gmail.com)
=end
require_relative '../utils/list_node'
### ハッシュ探索(配列) ###
def hashing_search_array(hmap, target)
# ハッシュテーブルの key:目的の要素、value:インデックス
# ハッシュテーブルにこの key が存在しない場合、-1 を返す
hmap[target] || -1
end
### ハッシュ探索(連結リスト) ###
def hashing_search_linkedlist(hmap, target)
# ハッシュテーブルの key:目的の要素、value:ノードオブジェクト
# ハッシュテーブルにこの key が存在しない場合、None を返す
hmap[target] || nil
end
### 実行用コード ###
if __FILE__ == $0
target = 3
# ハッシュ探索(配列)
nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8]
# ハッシュテーブルを初期化する
map0 = {}
for i in 0...nums.length
map0[nums[i]] = i # key:要素、value:インデックス
end
index = hashing_search_array(map0, target)
puts "目的の要素 3 のインデックス = #{index}"
# ハッシュ探索(連結リスト)
head = arr_to_linked_list(nums)
# ハッシュテーブルを初期化する
map1 = {}
while head
map1[head.val] = head
head = head.next
end
node = hashing_search_linkedlist(map1, target)
puts "目的のノードの値 3 に対応するノードオブジェクトは #{node}"
end