文章

16

粉丝

33

获赞

2

访问

2.7k

头像
动态查找的问题 题解:使用hash表
P5127
发布于2024年3月29日 20:02
阅读数 134

## 分析——采用hash表
- 数据总数不超过十万,可以将hash表长设置为十万,采用最简单的线性探测法,一旦发生冲突就往后找

### 代码

// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;
int num[100001];//静态内存区默认的初始值是0

int main() {
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++) {
		int temp;
		scanf("%d", &temp);
		int j = 0;
		while (true) { //线性探测法
			if (num[(temp + j) % 100000] == 0) {
				num[(temp + j) % 100000] = temp;
				break;
			}
			j++;
		}
	}
	int m;
	scanf("%d", &m);
	for (int i = 0; i < m; i++) {
		int temp;
		scanf("%d", &temp);
		int j = 0;
		while (true) { //线性探测法
			if (num[(temp + j) % 100000] == 0) {
				printf("no\n");
				num[(temp + j) % 100000] = temp;
				break;
			} else if (num[(temp + j) % 100000] == temp) {
				printf("find\n");
				break;
			}
			j++;
		}
	}

	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发