📅  最后修改于: 2023-12-03 15:00:13.170000             🧑  作者: Mango
本程序旨在计算给定数组中每个元素的频率。它将数组作为输入,并返回一个包含每个元素及其频率的子数组。
下面是计算数组中每个元素的频率的实现思路:
以下是用C语言实现计算数组中每个元素频率的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int key;
int value;
} KeyValue;
// 哈希表存储每个元素及其频率
KeyValue* hashMap = NULL;
int hashMapSize = 0;
void addToHashMap(int elem) {
if (hashMap == NULL) {
hashMap = (KeyValue*)malloc(sizeof(KeyValue));
} else {
hashMap = (KeyValue*)realloc(hashMap, (hashMapSize + 1) * sizeof(KeyValue));
}
hashMap[hashMapSize].key = elem;
hashMap[hashMapSize].value = 1;
hashMapSize++;
}
int findInHashMap(int elem) {
for (int i = 0; i < hashMapSize; i++) {
if (hashMap[i].key == elem) {
return i;
}
}
return -1;
}
void calculateFrequency(int* arr, int size) {
for (int i = 0; i < size; i++) {
int index = findInHashMap(arr[i]);
if (index != -1) {
hashMap[index].value++;
} else {
addToHashMap(arr[i]);
}
}
}
void printFrequencies() {
printf("|Element | Frequency |\n");
printf("|--------|-----------|\n");
for (int i = 0; i < hashMapSize; i++) {
printf("| %d | %d |\n", hashMap[i].key, hashMap[i].value);
}
}
void freeHashMap() {
free(hashMap);
}
int main() {
int arr[] = {1, 2, 1, 3, 4, 2, 3, 2, 1};
int size = sizeof(arr) / sizeof(arr[0]);
calculateFrequency(arr, size);
printFrequencies();
freeHashMap();
return 0;
}
此程序假设输入数组中的元素为整数。您可以根据需要更改int
到适合的数据类型。在main()
函数中定义输入数组arr
和其大小,然后调用calculateFrequency()
函数计算频率,并使用printFrequencies()
函数打印结果。
以下是使用示例数组{1, 2, 1, 3, 4, 2, 3, 2, 1}
运行程序的输出示例:
| Element | Frequency | |---------|-----------| | 1 | 3 | | 2 | 3 | | 3 | 2 | | 4 | 1 |