以下是一个使用哈希表遍历查找预定义值的代码示例:
def find_value_in_array(array, target):
# 创建空的哈希表
hash_table = {}
# 遍历数组,将数组元素添加到哈希表中
for i in range(len(array)):
hash_table[array[i]] = i
# 查找目标值在哈希表中的索引
if target in hash_table:
return hash_table[target]
else:
return -1
# 示例用法
array = [2, 5, 9, 13, 6, 1]
target = 6
index = find_value_in_array(array, target)
if index != -1:
print(f"找到目标值 {target} 在数组中的索引为 {index}")
else:
print(f"目标值 {target} 不在数组中")
这个代码示例中,我们首先创建了一个空的哈希表 hash_table
。然后,我们使用一个循环遍历数组 array
,将数组元素作为键,将其索引作为值,添加到哈希表中。最后,我们通过判断目标值 target
是否在哈希表中,来确定其在数组中的索引。如果找到了目标值,我们返回其索引;否则,返回 -1 表示目标值不在数组中。
上一篇:遍历哈希表并保存到不同的行
下一篇:遍历哈希并返回新形成的哈希