温馨提示×

c语言一维数组删除重复值的方法是什么

小亿
117
2023-11-06 12:46:23
栏目: 编程语言

一维数组删除重复值的方法可以通过以下步骤实现:

  1. 定义一个新数组,用于存储不重复的元素。
  2. 遍历原数组,将数组中的每个元素与新数组中的元素进行比较,如果不存在于新数组中,则将其添加到新数组中。
  3. 最后,新数组中存储的就是原数组中的不重复元素。

以下是一个示例代码:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int arr[MAX_SIZE], uniqueArr[MAX_SIZE];
    int n, k = 0, isUnique;

    printf("Enter the size of the array: ");
    scanf("%d", &n);

    printf("Enter the elements of the array: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Check for unique elements
    for (int i = 0; i < n; i++) {
        isUnique = 1;
        for (int j = 0; j < k; j++) {
            if (arr[i] == uniqueArr[j]) {
                isUnique = 0;
                break;
            }
        }
        if (isUnique) {
            uniqueArr[k++] = arr[i];
        }
    }

    printf("Array after removing duplicates: ");
    for (int i = 0; i < k; i++) {
        printf("%d ", uniqueArr[i]);
    }

    return 0;
}

这段代码首先输入了一个数组的大小和元素,然后遍历该数组,将不重复的元素存储在一个新的数组中,最后输出新数组中的元素。

0