您的位置:首页 > 其它

40.百度研发笔试题(栈、算法)

2012-03-22 17:13 211 查看
40.百度研发笔试题(栈、算法)

引用自:zp155334877

1)设计一个栈结构,满足一下条件:min,push,pop操作的时间复杂度为O(1)。

2)一串首尾相连的珠子(m个),有N种颜色(N<=10),

设计一个算法,取出其中一段,要求包含所有N中颜色,并使长度最短。

并分析时间复杂度与空间复杂度。

代码见下:

最短摘要的生成http://blog.csdn.net/v_july_v/article/details/6890054

3)设计一个系统处理词语搭配问题,比如说 中国 和人民可以搭配,

则中国人民 人民中国都有效。要求:

*系统每秒的查询数量可能上千次;

*词语的数量级为10W;

*每个词至多可以与1W个词搭配

当用户输入中国人民的时候,要求返回与这个搭配词组相关的信息。

方案:

步骤:

1. 分词.

2. 判断是否搭配

一。分词的判断

如果不考虑歧义,可以用wm基于shift表的词表匹配方法,在O(length(input))时间内完成分词。

如果考虑歧义,用专用分词系统。时间复杂度待查。

暂时不考虑歧义。

wm表占用内存大概5M以内.

二。判断是否搭配

用二维向量表示10w个词之间的搭配信息。每个词-词搭配信息占用一个bit,共 10w * 10w bit,大概

160MByte.

分词完成后,可以在O(1)时间内完成搭配信息的查询。

上述处理在普通PC(AMD 双核2.5G Hz,2G内存)上可以在一百-五百微秒时间范围内完成,即每秒至少可以

处理两千次查询。

参考:http://blog.sina.com.cn/s/blog_63ce05ca0100u2b5.html

//coder:Lee,20120322

#include<iostream>

#include<cassert>

using namespace std;

struct Index

{

int front;

int behind;

};

Index ShortestSectionWithFullColors(int *A,int nLength,int nColors)

{

Index index;

int pBegin=0;

int pEnd=0;

int *hash=new int[nColors+1];

int nTargetLen=0;

int nShortestLen=nLength+1;

for (int i=0;i<nColors+1;i++)

{

hash[i]=0;

}

while(true)

{

while(nTargetLen!=nColors)

{

hash[A[pEnd]]++;

if(hash[A[pEnd]]==1)

nTargetLen++;

pEnd++;

if(pEnd>=nLength)

pEnd=0;

}

while(nTargetLen==nColors)

{

if((pEnd-pBegin+nLength)%nLength<nShortestLen)

{

nShortestLen=(pEnd-pBegin+nLength)%nLength;

index.front=pEnd;

index.behind=pBegin;

}

hash[A[pBegin]]--;

if(hash[A[pBegin]]==0)

nTargetLen--;

pBegin++;

if(pBegin>=nLength)

break;

}

if(pBegin>=nLength)

break;

}

return index;

}

int main()

{

int A[]={1,2,1,2,1,1,3,1,1,3};

int nLen=sizeof(A)/sizeof(int);

Index index=ShortestSectionWithFullColors(A,nLen,3);

for (int i=index.behind;i!=index.front;)

{

cout<<A[i]<<" ";

i++;

i=(i+nLen)%nLen;

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: