Remove Duplicates in C Arrays
There are two methods to remove duplicate elements from an array.
- Create a new array, go through the original array, and store unique elements in the new array.
- Copy the new array back to the original array.
int removeDuplicates(int arr[], int n) {
if (n == 0 || n == 1) {
return n;
}
int temp[n];
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i + 1]) {
temp[j++] = arr[i];
}
}
temp[j++] = arr[n - 1];
for (int i = 0; i < j; i++) {
arr[i] = temp[i];
}
return j;
}
- Using two pointers, one pointing to the current element and the other pointing to the next different element.
- Traverse the original array, and if the current element is not the same as the next element, copy the next element to the position after the current element.
int removeDuplicates(int arr[], int n) {
if (n == 0 || n == 1) {
return n;
}
int j = 0;
for (int i = 0; i < n - 1; i++) {
if (arr[i] != arr[i + 1]) {
arr[j++] = arr[i];
}
}
arr[j++] = arr[n - 1];
return j;
}
Both of these methods can achieve the function of removing duplicate elements in an array, the specific choice of method depends on the specific situation and requirements.