一种函数,用于检查每个元素在数组中出现的次数

我正在创建一个列出数组的函数,并说明每个元素出现的次数。

到目前为止我自己想到的是我应该遍历数组并且应该有一个计数器来跟踪它出现的次数,然后是第二个数组来放置该计数器的值与值对应在第一个数组中。

但我无法弄清楚一个算法来搜索每个值是否在循环内重复。

代码示例已经简化,并且有更多注释

以下是一些建议的步骤:
1)假设int a[]被排序(为了便于计数)(升序或降序,无关紧要)。
2)创建单独的数组以保持找到的结果在哪里
一个, num[]存储唯一值,和
second cnt[]存储找到的值的数量。
3)循环排序数组。
4) in循环,存储唯一值,以及keep数组中的出现次数。

排序例程qsort()是一个概念,如果你刚刚开始,你将在后面学习,(暂时不要分心) 但是请注意这个例子的部分解决你的问题,寻找评论“看这里“ 。 如上所述,它循环遍历数组,并存储有关数字何时发生变化的信息,以及每个数字变化的数量。

这是一个小代码示例:

看看评论,知道在哪里集中注意力设置计数器等。

 #include  #define sizea 100 //to make variable declarations easier and consistent int num[sizea];//unless array has all unique numbers, will never use this many int cnt[sizea];//same comment int cmpfunc (const void * a, const void * b);//DISREGARD for now (it just works) int main(void) { //a[] is created here as an unsorted array... int a[sizea]={1,3,6,8,3,6,7,4,6,9,0,3,5,12,65,3,76,5,3,54, 1,3,6,89,3,6,7,4,6,9,0,4,5,12,65,3,76,5,3,54, 1,9,6,8,3,45,7,4,6,9,0,89,5,12,65,3,76,5,3,54, 6,3,6,8,3,6,7,4,6,9,0,23,5,12,65,3,76,5,3,54, 1,3,6,90,3,6,7,4,6,9,0,5,5,12,65,3,76,5,3,54}; int i, j, ncount; for(i=0;i 

对于包含的数组示例,以下是使用此代码的结果:

在此处输入图像描述

首先,您必须使用您拥有的整数及其出现次数来定义列表

 struct linked_list { int value; int numOf; linked_list *next; }; 

然后你必须具有操作该列表的function,例如创建列表,将项目推送到该列表,在该列表中查找节点并将其打印到列表中。

 linked_list* newItem(int value) { linked_list * temp = (linked_list *)malloc(sizeof(linked_list)); (*temp).value = value; (*temp).numOf = 1; return temp; } linked_list* findItem(linked_list *head, int value) { linked_list *counter = head; while (counter != NULL && (*counter).value != value) { counter = (*counter).next; } return counter; } void pushToList(linked_list **head, linked_list *item) { (*item).next = *head; *head = item; } void printList(linked_list *head) { while (head != NULL) { printf("%d:%d\n", (*head).value, (*head).numOf); head = (*head).next; } } 

您必须学习列表才能了解它们的运作方式。 然后你的代码逻辑是这样的:

 linked_list *duplicate = NULL; int i; int list[11] = { 1, 2, 3, 4, 1, 2, 3, 4, 0, 1, 2 }; for (i = 0; i < 11; i++) { linked_list *current = findItem(duplicate, list[i]); if (current == NULL) pushToList(&duplicate, newItem(list[i])); else (*current).numOf++; } printList(duplicate); while (1); return 0; 

(我必须释放列表,但我没有在此代码中:P)

我列出了可能重复的项目/元素。 我从数组的开头开始。 我检查数组的第一个元素,然后检查它是否在重复列表中。 如果我在列表中找不到它,我会在重复列表中创建一个新记录,其中包含1个出现次数。 然后我检查剩下的,如果它们出现在列表中,我将出现次数加一,如果不是,我会创建一个新记录。 最后,我的列表将包含每个号码及其出现次数。

如果数据差异是常数,则此代码需要O(n)步。 如果您的数据差异随元素数量的增加而增加,则需要更多步骤。

在执行步骤的数量和存储器分配方面,这种方法在许多情况下比排序算法更好。

我发布了一个伪代码,以帮助您使用您说无法理解的算法。 我希望这会鼓励你启动代码。

 //store the first number in a variable and find //how many times it occurs in the array, repeat this for all //the elements in the array int current = arr[0]; int i=0, count=0; for(i=0; i < arr.length;i++){ // loop through all the elements of the array if(arr[i]==current) { count++; // if current number is same as the number you are looking for // then increment the counter } // end of if-loop }