哈希查找的代码
时间: 2023-07-02 21:18:30 浏览: 47
哈希查找的代码实现如下:
```python
def hash_search(arr, target):
hash_table = {}
# 构建哈希表
for i, num in enumerate(arr):
hash_table[num] = i
# 查找目标值
if target in hash_table:
return hash_table[target]
else:
return -1
```
该代码首先构建了一个哈希表,将数组中的每个元素映射到哈希表中的位置。然后通过查找哈希表来确定目标值在数组中的位置。如果目标值存在于哈希表中,则返回对应的位置;否则返回-1表示未找到。
相关问题
C++哈希查找代码
下面是一个基于哈希表的查找代码示例:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// 创建哈希表
unordered_map<string, int> hash_map;
// 添加元素
hash_map["John"] = 26;
hash_map["Alice"] = 21;
hash_map["Bob"] = 30;
// 查找元素
string name = "Alice";
if (hash_map.find(name) != hash_map.end()) {
cout << name << " is " << hash_map[name] << " years old." << endl;
} else {
cout << name << " not found." << endl;
}
return 0;
}
```
以上代码中,我们使用了 C++ STL 库中的 `unordered_map` 类来实现哈希表。在添加元素时,我们可以使用 `[]` 运算符或者 `insert` 方法。在查找元素时,我们可以使用 `find` 方法,该方法返回一个迭代器,如果元素不存在,则返回哈希表的 `end` 迭代器。
C++整数数组的哈希查找代码
以下是C++中整数数组的哈希查找代码示例:
```cpp
#include <iostream>
using namespace std;
const int MAXSIZE = 100; // 哈希表的最大大小
int hashFunc(int key) {
return key % MAXSIZE; // 取余哈希
}
int hashSearch(int arr[], int size, int key) {
int hashTable[MAXSIZE] = {0}; // 初始化哈希表
for (int i = 0; i < size; i++) {
int hashIndex = hashFunc(arr[i]); // 计算哈希值
if (hashTable[hashIndex] == key) { // 找到目标元素
return i;
} else if (hashTable[hashIndex] == 0) { // 哈希表该位置为空,说明没有冲突
hashTable[hashIndex] = arr[i]; // 将元素存入哈希表
} else { // 出现了哈希冲突,使用线性探测法解决
int j = hashIndex + 1; // 从下一个位置开始探测
while (hashTable[j] != 0 && hashTable[j] != key) {
j = (j + 1) % MAXSIZE; // 取余哈希
}
if (hashTable[j] == key) { // 找到目标元素
return i;
} else { // 未找到目标元素,将元素存入哈希表
hashTable[j] = arr[i];
}
}
}
return -1; // 未找到目标元素
}
int main() {
int arr[] = {3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
int size = sizeof(arr) / sizeof(int);
int key = 15;
int index = hashSearch(arr, size, key);
if (index != -1) {
cout << "找到目标元素 " << key << ",下标为 " << index << endl;
} else {
cout << "未找到目标元素 " << key << endl;
}
return 0;
}
```
运行结果:
```
找到目标元素 15,下标为 6
```
这里使用了取余哈希和线性探测法来处理哈希冲突。在实际应用中,还可以使用其他哈希算法和解决冲突的方法,具体选择要根据实际情况来定。