【发布时间】:2017-05-03 09:35:55
【问题描述】:
我有下一个问题: 我的程序读取两个数组并将第一个数组的每个元素与第二个数组的每个元素相乘。我必须计算小于给定数字的结果数量。我的代码工作正常,但我需要找到更快的算法。
这是我的代码:
void sort(int *array, int length)
{
int index, jndex = 0, aux, compElPoz;
for(index = 1; index < length; index++)
{
jndex = index - 1;
compElPoz = index;
while(array[compElPoz] < array[jndex])
{
aux = array[compElPoz];
array[compElPoz] = array[jndex];
array[jndex] = aux;
if(jndex > 0)
jndex--;
compElPoz--;
}
}
}
int main()
{
unsigned int n, in, jn, nr = 0, p, m;
scanf("%u %u", &n, &p);
int ar[n];//1st array
for(in = 0; in < n; in++)
{
scanf("%u", &ar[in]);//reading the 1st array
}
scanf("%u", &m);
int arr[m];//2nd array
for(in = 0; in < m; in++)
{
scanf("%u", &arr[in]);//reading the 2nd array
}
sort(arr, m);//sorting the 2nd array
for(in = 0; in < n; in++)
{
for(jn = 0; jn < m; jn++)
{
if(ar[in] * arr[jn] < p)
nr++;
else
break;
}
}
printf("%d", nr);
return 0;
}
所以我必须阅读 ar[] 和 arr[] 和 p。 这是一个例子:
n = 5
p = 99
ar[5] = {1, 2, 3, 4, 5}
m = 2
arr[2] = {34, 25}
程序将打印 5,因为 1 * 34
【问题讨论】:
-
这个问题属于这里:codereview.stackexchange.com
-
对 ar[] 数组也进行排序。
-
做到了,但还是不够快
-
@MichaelWalz 我必须删除它并在 codereview 上询问它还是可以移动它吗?
-
@Timotei:仅排序是不够的,您必须利用数组已排序的事实。您可以跳过大部分内部循环,方法是从您之前停止的位置开始,然后在已排序的第二个数组中查找下一个项目,其中第一个项目的当前项目的产品低于您的阈值。您将只遍历每个数组一次,但将向后遍历第二个数组。