题解 | #明明的随机数#

明明的随机数

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-04 18:02
好不容易拿到了字节Offer,鼠鼠做后端的,但家里人觉得可能被裁员不稳定,让鼠鼠去投国企,现在好纠结到底该咋选
文档传偷助手:该投就投吧,不过建议别放弃offer 拿到手里的才是最好的
投递字节跳动等公司8个岗位
点赞 评论 收藏
分享
门口唉提是地铁杀:之前b站被一个游戏demo深深的吸引了。看up主页发现是个初创公司,而且还在招人,也是一天60。二面的时候要我做一个登录验证和传输文件两个微服务,做完要我推到github仓库,还要我加上jaeger和一堆运维工具做性能测试并且面试的时候投屏演示。我傻乎乎的做完以后人家跟我说一句现在暂时不招人,1分钱没拿到全是白干
你的秋招第一场笔试是哪家
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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