数组去重函数,只用stdio.h
时间: 2024-09-26 10:12:00 浏览: 40
数组去重函数通常涉及到遍历数组并检查元素是否已存在其他位置。由于`stdio.h`主要是输入输出库,并不直接提供数组处理的功能,我们通常会使用标准库`stdlib.h`和`stdbool.h`来辅助实现。下面是一个简单的示例,假设我们有一个整数数组:
```c
#include <stdio.h>
#include <stdbool.h>
bool isDuplicate(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] == arr[j])
return true;
}
}
return false;
}
void removeDuplicates(int arr[], int n) {
bool duplicateExists = isDuplicate(arr, n);
if (!duplicateExists)
return;
int uniqueArr[n];
int uniqueIndex = 0;
for (int i = 0; i < n; i++) {
if (!isDuplicate(uniqueArr, uniqueIndex)) {
uniqueArr[uniqueIndex++] = arr[i];
}
}
// 如果有重复,调整原始数组大小并复制非重复元素
for (int i = uniqueIndex; i < n; i++)
arr[i] = arr[uniqueIndex++];
printf("去重后的数组:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 5, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
removeDuplicates(arr, n);
return 0;
}
```
在这个例子中,`isDuplicate()`函数用于检测是否有重复元素,`removeDuplicates()`函数则创建一个新的去重数组。注意这个方法并不节省原始数组的空间,如果内存有限,可以考虑使用其他数据结构如链表。
阅读全文
相关推荐

















