ACM超级水题-------统计不同数字的个数

统计不同数字的个数

Time Limit:1000MS  Memory Limit:65536K
Total Submit:3007 Accepted:1858

Language: not limited

Description

由键盘输入20个整数,统计不同数字的个数。

Input

 

Output

 

Sample Input

70  5  14  22  19  2  99  67  13  66  5  93  44  38  22  11  39  22  33  11

 

Sample Output

16

 

Hint

因为5有1个重复数字,11有1个重复数字,22有2个重复数字

Source

 

Provider

checkie

 

 

 

我的做法如下:

法1:静态分配数组内存 #include<stdio.h> int main(void) { int iary[20] ; int temp = 0 ; int i = 0 ; int n = 20 ; int j = 0 ; for(i = 1 , scanf("%d",&iary[0]) ; i < 20 ; i++ ) { scanf("%d",&temp) ; for(j = 0 ; j < i ; j++) { if(temp == iary[j]) { n-- ; break ; } } if( j == i) { iary[i] = temp ; } } printf("%d",n) ; return 0 ; } 法2:动态分配数组内容。 #include<stdio.h> #include<stdlib.h> int main(void) { int *iary = (int *)malloc(sizeof(int)) ; int temp = 0 ; int i = 0 ; int n = 20 ; int j = 0 ; for(i = 1 , scanf("%d",&iary[0]) ; i < 20 ; i++ ) { scanf("%d",&temp) ; for(j = 0 ; j < i ; j++) { if(temp == iary[j]) { n-- ; break ; } } if( j == i) { iary = (int *)realloc(iary,(i+1) * sizeof(int)) //重新分配内存空间 iary[i] = temp ; } } printf("%d",n) ; return 0 ; } /*想法*/ ///其实做法1与做法2可以说是完全相同的做法,只不过做法1中,我事先分配了20个int的空间给iary数组,因为不重复的数字最多只有20个。 //而做法2中,我选择了动态分配内存的方法来保存不重复的数字,目的是想节省空间。因为20个数字中,如果有重复的出现,就不应该再把它与之后的元素进行判断。 //但是,事实上做法2中是多了调用realloc函数这一步,只不过,我没有想到的是多了这一步,时间复杂度竟然比做法1多出3MS。。。看来,我还是想多了。

 

 

法1:

 

 

 

 

法2:

 

 

 

你可能感兴趣的:(ACM超级水题-------统计不同数字的个数)