C语言中如何查找数组中出现多次的元素?
数组是相同数据类型元素的容器,长度需要预先定义。数组中的元素可以以任何顺序出现,并且可以重复出现任意次数。因此,在本程序中,我们将查找数组中出现多次的元素。
问题描述 - 我们给定一个数组 arr[],我们需要找到数组中哪些元素是重复的,并输出它们。
让我们举个例子来更好地理解这一点。
示例,
Input: arr[] = {5, 11, 11, 2, 1, 4, 2}
Output: 11 2解释
我们有一个包含一些元素的数组 arr,首先我们将比较数组中下一个元素的元素,在用于查找数组中重复元素的 duplicate 函数中。在 duplicate 函数中,我们使用循环来查找给定数组中的重复元素,我们将使用 if else 条件来检查数组元素的计数,如果数组元素出现一次,则计数为 1,如果出现多次,则计数将分别递增,如果计数大于 1,则该元素将打印在屏幕上。
算法
Input : arr[], n the length of array.
Step 1 : For i -> 0 to n, Follow step 2,
Step 2 : For each element of the array. Do :
Step 2.1 : For j -> i to n repeat step 2.2 - 2.3.
Step 2.2 : if (arr[i] == arr[j]) -> print arr[i]
Step 2.3 : else {// do nothing}示例
#include <stdio.h>
int main() {
int arr[] = {21, 87, 212, 109, 41, 21};
int n=7;
printf("The repeat elements of the array are : ");
int *count = (int *)calloc(sizeof(int), (n - 2));
int i;
for (i = 0; i < n; i++) {
if (count[arr[i]] == 1)
printf(" %d ", arr[i]);
else
count[arr[i]]++;
}
return 0;
}输出
The repeat elements of the array are : 21
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP