Trade off另外一个实例

来源:互联网 发布:mac不用u盘装win7系统 编辑:程序博客网 时间:2024/05/22 17:47

 

今天看到的一个地方,忽然看不通了,居然说能够把一个数组的初始化可以从N,变成0

 

想了半个多小时。。没想出来。。。

 

55555555.。。。。水平还是不够啊。。。,看了答案,回来自己把这个算法实现了下

算法还是很简单的,不多说了,真想知道的话,看程序吧。。。

哈哈,不要骂我懒哦~~~

由于数组在创建的时候是不会被初始化的(这是在C中间,JAVA中数组属于对象,会有对象的初始化,每个都会被赋系统默认值),这样在运算之初需要对数组进行手动的初始化。这样就需要N的时间,但是怎么变成0呢

看程序吧

  1. #include<stdio.h>
  2. int  a[100];
  3. int  from[100];
  4. int  to[100];
  5. int top=0;
  6. void access(int accessindex,int value);
  7. int getvalue(int accessindex);
  8. int main()
  9. {
  10. int index=0;
  11. for(;index<23;index++)
  12.     access(rand()%100,rand());
  13. for(index=0;index<100;index++)
  14.     printf("%d----------%d/n",index,getvalue(index));
  15. }
  16. void access(int accessindex,int value)
  17. {
  18. if(top!=0&&from[accessindex]<top&&to[from[accessindex]]==accessindex)
  19.     {
  20.     printf("%d --access after initialized and succeeded./n",accessindex);
  21.     a[accessindex]=value;
  22.     }
  23. else
  24.     {
  25.     printf("%d --first time to be accessed and now initializing to be as %d/n",accessindex,value);
  26.     from[accessindex]=top;
  27.     to[top]=accessindex;
  28.     top++;
  29.     a[accessindex]=value;
  30.     }
  31. }
  32. int getvalue(int accessindex)
  33. {
  34. int result;
  35. if(top!=0&&from[accessindex]<top&&to[from[accessindex]]==accessindex)
  36.     {
  37.     printf("%d --access after initialized and succeeded./n",accessindex);
  38.     result=a[accessindex];
  39.     }
  40. else
  41.     {
  42.     printf("%d ---first time to be accessed and now initializing to be as 0./n",accessindex);
  43.     from[accessindex]=top;
  44.     to[top]=accessindex;
  45.     top++;
  46.     a[accessindex]=0;
  47.     result=0;
  48.     }
  49. return result;
  50. }

其实啊,就是这样了。实现倒是简单,但是想法太。。太。。。太。。。。。太难以捉摸了

 

需要另外的2个的两个大小相等的数组来做辅助,占用空间太多了。典型的空间来换时间。

发出来只是让大家看看而已。。。哈哈

 

原创粉丝点击