C语言如何判断数字是否连续

2025-06-19 15:34:16

#include

#include

// 哈希表节点

struct HashNode {

int key;

struct HashNode *next;

};

// 创建哈希表

struct HashNode createHashTable(int size) {

struct HashNode table = (struct HashNode)malloc(size * sizeof(struct HashNode*));

for (int i = 0; i < size; i++) {

table[i] = NULL;

}

return table;

}

// 哈希函数

int hashFunction(int key, int size) {

return key % size;

}

// 插入哈希表

void insertHashTable(struct HashNode table, int size, int key) {

int hashIndex = hashFunction(key, size);

struct HashNode* newNode = (struct HashNode*)malloc(sizeof(struct HashNode));

newNode->key = key;

newNode->next = table[hashIndex];

table[hashIndex] = newNode;

}

// 查找哈希表

int searchHashTable(struct HashNode table, int size, int key) {

int hashIndex = hashFunction(key, size);

struct HashNode* node = table[hashIndex];

while (node != NULL) {

if (node->key == key) {

return 1;

}

node = node->next;

}

return 0;

}

int areNumbersConsecutive(int arr[], int n) {

int min = arr[0], max = arr[0];

// 找到数组中的最小值和最大值

for (int i = 1; i < n; i++) {

if (arr[i] < min) {

min = arr[i];

}

if (arr[i] > max) {

max = arr[i];

}

}

// 创建哈希表

struct HashNode hashTable = createHashTable(n);

// 将数组中的每个数字存储在哈希表中

for (int i = 0; i < n; i++) {

insertHashTable(hashTable, n, arr[i]);

}

// 检查哈希表中是否包含从最小值到最大值的所有数字

for (int i = min; i <= max; i++) {

if (!searchHashTable(hashTable, n, i)) {

return 0; // 不连续

}

}

return 1; // 连续

}

int main() {

int arr[] = {5, 2, 3, 4, 6};

int n = sizeof(arr) / sizeof(arr[0]);

if (areNumbersConsecutive(arr, n)) {

printf("数组中的数字是连续的n");

} else {

printf("数组中的数字是不连续的n");

}

return 0;

}

红莲婚怎么那么难
笔记本三包有效期是多久