C語言可以使用以下方法實現數組去重:
int removeDuplicates(int arr[], int n)
{
int i, j, k;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n;) {
if (arr[j] == arr[i]) {
for (k = j; k < n; k++) {
arr[k] = arr[k + 1];
}
n--;
} else {
j++;
}
}
}
return n;
}
#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int removeDuplicates(int arr[], int n) {
int i, j;
if (n == 0 || n == 1)
return n;
qsort(arr, n, sizeof(int), cmpfunc);
i = 0;
for (j = 1; j < n; j++) {
if (arr[j] != arr[i]) {
i++;
arr[i] = arr[j];
}
}
return i + 1;
}
int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int result = removeDuplicates(arr, n);
printf("Array after removing duplicates: ");
for (int i = 0; i < result; i++) {
printf("%d ", arr[i]);
}
return 0;
}
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
void removeDuplicates(int arr[], int n) {
int hash[MAX_SIZE] = {0};
int i, j;
for (i = 0; i < n; i++) {
if (hash[arr[i]] == 0) {
hash[arr[i]] = 1;
printf("%d ", arr[i]);
}
}
}
int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array after removing duplicates: ");
removeDuplicates(arr, n);
return 0;
}