#include <stdio.h> #include <stdlib.h> // 函数用于移除数组中的重复元素并返回新数组的大小 int removeDuplicates(int* arr, int size, int** newArray) { if (size <= 0) return 0; // 动态分配内存给新的数组 *newArray = (int*)malloc(size * sizeof(int)); if (*newArray == NULL) { printf("Memory allocation failed\n"); exit(1); } int newSize = 0; for (int i = 0; i < size; i++) { int isDuplicate = 0; // 检查当前元素是否已经在新数组中存在 for (int j = 0; j < newSize; j++) { if ((*newArray)[j] == arr[i]) { isDuplicate = 1; break; } } if (!isDuplicate) { (*newArray)[newSize++] = arr[i]; } } return newSize; } int main() { int array[] = {1, 2, 3, 2, 4, 5, 3, 6, 1}; int size = sizeof(array) / sizeof(array[0]); int* newArray; int newSize = removeDuplicates(array, size, &newArray); // 输出去重后的数组 printf("Array after removing duplicates: "); for (int i = 0; i < newSize; i++) { printf("%d ", newArray[i]); } printf("\n"); // 释放动态分配的内存 free(newArray); return 0; }
标签:重复,元素,int,数组,去掉,include,size From: https://www.cnblogs.com/xhu218/p/18677512