您的位置:首页 > 职场人生

一道简单的面试题

2012-04-20 17:58 274 查看
设初始区间为seq0 [0.0,1,0],产生一个随机数插入原来区间形成新区间seq1(假设产生0.7,则seq1=[0.0,0.7,1.0])。对seq1中的区间的子相邻区间(如[0.0,0.7]和[0.7,1.0])取最大值,再次在此区间产生随机数并插入...如此不断重复。

算法很简单,维护一个链表即可。每产生一个数所需的时间复杂度O(N),直接上代码(有优化余地):

#include <stdio.h>
#include <stdlib.h>

typedef struct TagNode{
float data;
struct TagNode* next;
} Node,*PNode;

float Generate(PNode entry){
PNode prev,cur;
float max=0.0;
float lb,ub,max_lb,max_ub;
if(entry->next==NULL)return 0.0;
cur=entry;
max_lb=0.0;
max_ub=0.0;
do{
prev=cur;
cur=cur->next;
lb=prev->data;
ub=cur->data;
if(max<(ub-lb)){
max=ub-lb;
max_lb=lb;
max_ub=ub;
}
}while(cur&&cur->next);
//generate a data from (max_lb,max_ub)
return max_lb+max*(rand()%1000)/1000.0;
}

bool InsertNode(PNode entry,PNode toinsert){
PNode cur,prev;
prev=entry;
cur=entry->next;
if(toinsert->data<entry->data)return false;
while(cur){
if(cur->data>toinsert->data){
prev->next=toinsert;
toinsert->next=cur;
return true;
}
prev=cur;
cur=cur->next;
}
return false;

}

void DumpList(PNode p){
while(p){
printf("%5.3f ",p->data);
p=p->next;
}
printf("\n");
}

void DestroyList(PNode p){
PNode prev=p;
do{
prev=p;
p=p->next;
free(prev);
}while(p);
}

void prob(){
PNode end=(PNode)malloc(sizeof(Node));
PNode beg=(PNode)malloc(sizeof(Node));
PNode head=beg;
PNode nextnode=NULL;
float nextdata;
beg->data=0.0;
beg->next=end;
end->data=1.0;
end->next=NULL;
while(getchar()!='q'){
fflush(0);
nextdata=Generate(head);
nextnode=(PNode)malloc(sizeof(Node));
nextnode->data=nextdata;
InsertNode(head,nextnode);
DumpList(head);
}
DestroyList(head);
}
void main(){
  prob();
}


上面的算法是插入一个数的时间复杂度为O(N),N个数的插入总的复杂度就是O(N^2)。问题来了,如果算法的要求是插入N个数要求总的插入时间复杂度最少呢?不知道有什么好方法,求不吝赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: