How to remove duplicate elements from an array in the C language?

To remove duplicate elements in a C language array, you can follow these steps:

  1. Iterate through the array and check if the current element is the same as the previous element.
  2. If they are the same, move all elements after the current element forward by one position and decrease the length of the array by one.
  3. If they are not the same, continue iterating through the next element.
  4. Repeat the above steps until the entire array has been traversed.

Here is a sample code:

#include<stdio.h>

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; // 返回去重后的数组长度
}

int main() {
    int arr[] = {1, 2, 2, 3, 4, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("原始数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    n = removeDuplicates(arr, n);

    printf("\n去重后的数组:");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

output results:

原始数组:1 2 2 3 4 4 5 
去重后的数组:1 2 3 4 5 
bannerAds