How to remove duplicate numbers from a one-dimensional array in C language?
To remove identical numbers in a one-dimensional array, you can use nested loops to iterate through the array, comparing each element to see if it is the same as any other element, and if so, delete that element.
Here is an example code:
#include <stdio.h>
void removeDuplicates(int arr[], int *size) {
int i, j, k;
for (i = 0; i < *size; i++) {
for (j = i + 1; j < *size;) {
if (arr[j] == arr[i]) {
// 元素相同,删除arr[j]
for (k = j; k < *size - 1; k++) {
arr[k] = arr[k + 1];
}
(*size)--; // 数组大小减1
} else {
j++;
}
}
}
}
int main() {
int arr[] = {1, 2, 3, 2, 4, 1, 5, 3};
int size = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
removeDuplicates(arr, &size);
printf("删除相同元素后的数组:");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
The result of the operation:
原始数组:1 2 3 2 4 1 5 3
删除相同元素后的数组:1 2 3 4 5
The removeDuplicates function in the above code is used to remove duplicate numbers in an array. It first uses a nested loop to iterate through the array, with the outer loop controlling the current element to compare and the inner loop iterating through all elements after the current one. If a duplicate element is found, the elements following it are moved forward one by one, reducing the size of the array by 1. Finally, the array with duplicate elements removed is outputted.