【发布时间】:2021-09-21 23:03:57
【问题描述】:
我正在尝试编写一个函数,将source1 中的所有值(也存在于source2 中)复制到destination 中,然后返回复制到目标中的元素数。
int common_elements(int length, int source1[length], int source2[length], int destination[length])
{
int counter = 0;
int i = 0;
while (i < length) {
int j = 0;
while (j < length) {
if ( source1[i] == source2[j]) {
destination[counter] = source1[i];
counter++;
}
j++;
}
i++;
}
return counter;
}
问题是例如给定(common_elements(5, {1,2,3,4,5}, {1,2,3,2,1}, [])),正确的输入应该是
1,2,3 return value: 3
但是,该程序正在考虑重复并产生:
1,1,2,2,3 return value: 5
这是不正确的。
我该如何补救?
【问题讨论】:
-
先对输入数组进行排序会更容易。但除此之外,只需在添加数字之前搜索输出数组即可。
-
您在做什么来尝试并解决重复问题?
标签: arrays c loops duplicates function-definition