40.百度研發筆試題(棧、算法)

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章