今天看到的一个地方,忽然看不通了,居然说能够把一个数组的初始化可以从N,变成0
想了半个多小时。。没想出来。。。
55555555.。。。。水平还是不够啊。。。,看了答案,回来自己把这个算法实现了下
算法还是很简单的,不多说了,真想知道的话,看程序吧。。。
哈哈,不要骂我懒哦~~~
由于数组在创建的时候是不会被初始化的(这是在C中间,JAVA中数组属于对象,会有对象的初始化,每个都会被赋系统默认值),这样在运算之初需要对数组进行手动的初始化。这样就需要N的时间,但是怎么变成0呢
看程序吧
- #include<stdio.h>
- int a[100];
- int from[100];
- int to[100];
- int top=0;
- void access(int accessindex,int value);
- int getvalue(int accessindex);
- int main()
- {
- int index=0;
- for(;index<23;index++)
- access(rand()%100,rand());
- for(index=0;index<100;index++)
- printf("%d----------%d/n",index,getvalue(index));
- }
- void access(int accessindex,int value)
- {
- if(top!=0&&from[accessindex]<top&&to[from[accessindex]]==accessindex)
- {
- printf("%d --access after initialized and succeeded./n",accessindex);
- a[accessindex]=value;
- }
- else
- {
- printf("%d --first time to be accessed and now initializing to be as %d/n",accessindex,value);
- from[accessindex]=top;
- to[top]=accessindex;
- top++;
- a[accessindex]=value;
- }
- }
- int getvalue(int accessindex)
- {
- int result;
- if(top!=0&&from[accessindex]<top&&to[from[accessindex]]==accessindex)
- {
- printf("%d --access after initialized and succeeded./n",accessindex);
- result=a[accessindex];
- }
- else
- {
- printf("%d ---first time to be accessed and now initializing to be as 0./n",accessindex);
- from[accessindex]=top;
- to[top]=accessindex;
- top++;
- a[accessindex]=0;
- result=0;
- }
- return result;
- }
其实啊,就是这样了。实现倒是简单,但是想法太。。太。。。太。。。。。太难以捉摸了
需要另外的2个的两个大小相等的数组来做辅助,占用空间太多了。典型的空间来换时间。
发出来只是让大家看看而已。。。哈哈