Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หา elements ซ้ำในอาร์เรย์

หาตัวเลขที่ปรากฏมากกว่า 1 ครั้งในอาร์เรย์

ตัวอย่าง

arr = {5, 11, 11, 2, 1, 4, 2} → Output: 11 2

วิธีที่ 1: Nested Loop (O(n²))

for (i = 0; i < n; i++)
    for (j = i+1; j < n; j++)
        if (arr[i] == arr[j]) print arr[i];

วิธีที่ 2: Counting Array (O(n)) - ต้องรู้ค่าสูงสุด

int max = 1000; // สมมติค่าไม่เกิน 1000
int count[1001] = {0};
for (i = 0; i < n; i++) count[arr[i]]++;
for (i = 0; i <= max; i++)
    if (count[i] > 1) printf("%d ", i);

โค้ดตัวอย่าง (ใช้ counting)

#include <stdio.h>
#include <stdlib.h>

int main() {
    int arr[] = {21, 87, 212, 109, 41, 21};
    int n = 6;
    int max = 212;
    int *count = calloc(max + 1, sizeof(int));

    printf("Repeated: ");
    for (int i = 0; i < n; i++) {
        if (count[arr[i]] == 1) printf("%d ", arr[i]);
        count[arr[i]]++;
    }
    free(count);
    return 0;
}

ผลลัพธ์

Repeated: 21