c - 删除数组中的重复元素而不进行排序 - 错误的输出
问题描述
我一直在尝试编写一个函数来删除整数数组中的重复元素而不对其进行排序。
对于该任务,我创建了一个名为 的函数removeDuplicateElements
,它获取一个数组及其字符串,并返回一个新的动态分配数组,该数组是原始数组的副本,其中删除了所有重复元素。此函数还通过引用返回新数组的大小。
我还在我的代码函数中使用了构建动态数组并打印它的函数。
这是我的代码:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void printArray(int *arr, int size);
int *buildArray(int size);
int *removeDuplicateElements(int *arr, int size, int *newSize);
void main() {
int size,newSize;
int *arr;
int *newArr;
printf("please enter a number for the size of array: ");
scanf("%d", &size);
printf("\nenter %d numbers: ", size);
arr = buildArray(size);
printf("\nthe array after removing the duplicate elements is: ");
newArr = removeDuplicateElements(arr, size, &newSize);
printArray(newArr, newSize);
free(newArr);
free(arr);
}
/* this function removes all duplicate elements in a given array */
int *removeDuplicateElements(int *arr, int size, int *newSize) {
int *newArr;
int count = size, i, j;
/* finding the new size of the original array with removal its duplicate elements */
for (i = 1; i < size; i++) {
for (j = 0; j < size; j++)
if (arr[i] == arr[j] && i != j) {
count--;
break;
}
}
newArr = (int*)malloc(count * sizeof(int)); /* dynamically allocating the new array */
count = 1;
newArr[0] = arr[0];
/*adding the elements in the new array without changing the order*/
for (i = 1; i < size; i++) {
for (j = 0; j < size; j++) {
if (arr[i] == arr[j] && i != j) {
break;
}
if (j == size - 1) {
newArr[count] = arr[i];
count++;
}
}
}
*newSize = count; /* updating the size of the new array */
return newArr; /* returning the address of new array */
}
void printArray(int *arr, int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int *buildArray(int size) {
int i;
int *arr = (int*)malloc(size * sizeof(int));
if (!arr) {
printf("ERROR! Not enough memory!\n");
exit(1);
}
for (i = 0; i < size; i++)
scanf("%d", &arr[i]);
return arr;
}
我得到了错误的代码输出,我不明白为什么
例如,对于以下数组size=5
:1 1 3 1 3
我得到了错误的输出1
,而预期的输出是
1 3
。
任何帮助,将不胜感激。
解决方案
您首先错误地计算了新数组的大小。对于您的示例输入,当您查看前 3 个时,它会扫描整个数组以查看有多少个 3 并发现有 2 个并断定它是重复的。然后它对第二个 3 做完全相同的事情。所以你最终得到新数组的大小为 1。
而不是扫描整个数组,您只想扫描数组以查找您正在检查的元素之前的元素。所以像这样。
for(i=1;i<size;i++)
{
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
{
count--;
break;
}
}
而对于填充新数组的代码也有同样的问题
for(i=1;i<size;i++)
{
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
{
break;
}
if(j==i)
{
newArr[count++]=arr[i];
}
}
推荐阅读
- apache-kafka - 安全地将秘密/令牌提供给 Kafka 连接器?
- svn - svn tag和svn版本的区别
- c - 尝试使用动态内存分配创建节点指针数组
- if-statement - ansible set_fact if-else 失败
- c++ - 如何使用 C++ 发送 APDU 命令?
- c# - C#弹性搜索查询,匹配多个查询
- git - Jenkins Pipeline:scm checkout 浅拷贝失败
- android - Flutter:触发 websocket 消息上的屏幕变化
- codeigniter-3 - Codeigniter hmvc 可以支持来自一个模块的多个控制器吗?
- angular - Angular中文本框中的限制值,用于bot max