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
廣告