在 C 語言中,可以通過以下幾種方法實現數組去重:
#include <stdio.h>
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;
}
int main() {
int arr[] = {1, 2, 3, 4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
n = removeDuplicates(arr, n);
printf("Array after removing duplicates: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
#include <stdio.h>
int removeDuplicates(int arr[], int n) {
int temp[n];
int j = 0;
for (int i = 0; i < n; i++) {
int duplicate = 0;
for (int k = 0; k < j; k++) {
if (arr[i] == temp[k]) {
duplicate = 1;
break;
}
}
if (!duplicate) {
temp[j++] = arr[i];
}
}
for (int i = 0; i < j; i++) {
arr[i] = temp[i];
}
return j;
}
int main() {
int arr[] = {1, 2, 3, 4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
n = removeDuplicates(arr, n);
printf("Array after removing duplicates: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int compare(const void* a, const void* b) {
return (*(int*)a - *(int*)b);
}
int removeDuplicates(int arr[], int n) {
qsort(arr, n, sizeof(int), compare);
int j = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != arr[i + 1]) {
arr[j++] = arr[i];
}
}
return j;
}
int main() {
int arr[] = {1, 2, 3, 4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
n = removeDuplicates(arr, n);
printf("Array after removing duplicates: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
以上三種方法都可以實現數組去重,具體選擇哪種方法取決于實際需求和性能要求。