【发布时间】:2021-03-25 19:35:05
【问题描述】:
您好,我需要帮助,我需要修复此代码,以便它只计算一次值
例如
输入:
25
38 25 36 4 1 1 10 37 45 21 37 42 21 1 50 9 50 42 6 39 10 14 17 11 20
10
36 42 2 15 28 42 3 23 8 50
输出:
4
这里的答案应该是 4 而不是 7。
#include <stdio.h>
int main()
{
int n, m, count = 0;
int array[1000];
int subarray[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d", &subarray[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (array[i] == subarray[j])
count++;
}
}
printf("%d\n", count);
}
【问题讨论】:
-
您的检查逻辑有缺陷,因为如果
n > m,内部循环将超出subarray的范围。使用调试器几分钟就会告诉你这一点。 -
你能添加代码的问题和目的吗?很难理解您要做什么。
-
一个小于 25 和 10 的例子会更容易帮助
-
我的建议是你对第一个数组进行排序,去除连续的重复项,然后使用二分查找从“子数组”中查找每个数字。您也应该对“子数组”中的重复项进行排序和删除。 (二分搜索需要排序才能工作,也使得删除重复项更容易。)
-
@Someprogrammerdude 数组排序后,无需删除重复项,只需在比较过程中跳过重复项,因为它们相邻,因此很容易找到。
标签: c algorithm data-structures