已知f[ ]与g[ ]两个整数数组,元素都已经从小到大排列,试编写程序算出f[ ]中每一个元素比g[ ]中元素大的个数总和。
我的答案:
#include <stdio.h>
int main()
{
int a[10]={1,2,4,7,9,12,13,15,16,20};
int b[10]={4,5,7,8,9,10,11,13,16,19};
int i,j,count=0;
for(i=0;i<10;i++)
{
for(j=9;j>=0;j--)
{
if(a[i]>b[j])
{
count+=j+1;
break;
}
}
}
printf("%d \n",count);
return 0;
}
标准答案:
int dominance_count(int f[], int g[], int m, int n)
{
int index_f, index_g;
int count;
count = index_f = index_g = 0;
while (index_f < m && index_g < n)
if (f[index_f] <= g[index_g])
index_f++;
else
index_g++, count += m - index_f;
return count;
}
/* ------------------------------------------------------ */
#include <stdio.h>
void main(void)
{
int x[] = { 1, 2, 4, 7, 9, 12, 13, 15, 16, 20};
int nx = sizeof(x)/sizeof(int);
int y[] = { 4, 5, 7, 8, 9, 10, 11, 13, 16, 19};
int ny = sizeof(y)/sizeof(int);
int dominance_count(int [], int [], int, int), i;
printf("\nDominance Count of two Increasing Arrays\n");
printf("\n # Array 1 Array 2");
printf("\n -- ------- -------");
for (i = 0; i < nx; i++)
printf("\n%3d%10d%10d", i, x[i], y[i]);
printf("\n\nThere are %d Dominance Pairs.",
dominance_count(x, y, nx, ny));
}
粗一看自己的答案貌似很简洁,仔细看标准答案,人家只用了一次循环就搞定了,而我用了双重循环,效率低了很多……