题解 | #明明的随机数#

明明的随机数

https://www.nowcoder.com/practice/3245215fffb84b7b81285493eae92ff0

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define HASH_SIZE 500

typedef struct{
    int key;
    bool is_used;//标记是否被使用
} HashEntry;

typedef struct{
    HashEntry* entries;//哈希表条目数组
} HashTable;

//初始化哈希表
void init_hash_table(HashTable *hash_table){
    hash_table->entries = (HashEntry*)malloc(HASH_SIZE* sizeof(HashEntry));
    for (int i=0; i<HASH_SIZE; i++) {
    hash_table->entries[i].is_used=false;
    }
}
int hash_function(int key){
    return key-1;//数组索引从0开始,所以要减1
}
//插入到哈希表
void insert_to_hash_table(HashTable* hash_table,int key){
    int index=hash_function(key);
    if (!hash_table->entries[index].is_used) {
    hash_table->entries[index].key=key;
    hash_table->entries[index].is_used=true;
    }
}
//释放哈希表内存
void free_hash_table(HashTable* hash_table){
    free(hash_table->entries);
}
//比较函数
int compare(const void* a,const void* b){
    return (*(int*)a-*(int*)b);
}
//主函数
int main() {
    int n;
    scanf("%d\n",&n);
 //初始化哈希表,并生成随机数字
 //申明一个HashTable类型的变量hash_table,并调用init_hash_table函数初始化它
 HashTable hash_table;
 init_hash_table(&hash_table);
//用循环生成1-500之间的数字,调用insert_to_hash_table将该随机数插入到哈希表中。
for (int i=0; i<n; i++) {
//若为生成随机数字则
//int random_number = rand() % 500 + 1; // 生成1到500之间的随机整数
int random_number=0;
scanf("%d\n",&random_number);
insert_to_hash_table(&hash_table, random_number);
}
//提取唯一数字,并排序
int unique_number[HASH_SIZE];
int count =0;
for (int i=0; i<HASH_SIZE; i++) {
if (hash_table.entries[i].is_used) {
unique_number[count++]=hash_table.entries[i].key;
}
}
//用qsort函数来排序
qsort(unique_number, count, sizeof(int), compare);
//输出排序后的数组unique_number
for (int i=0; i<count; i++) {
printf("%d\n",unique_number[i]);
}
//释放哈希表内存并结束程序
free_hash_table(&hash_table);
    return 0;
}

全部评论

相关推荐

07-01 19:00
门头沟学院 Java
点赞 评论 收藏
分享
求offer的大角牛:不吃香菜
点赞 评论 收藏
分享
星辰再现:裁员给校招生腾地方
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务