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

腾讯2016年9月14号面试笔试题

2015-09-14 00:19 459 查看
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <vector>
#define DefaultSize 13
//文本中的大量字符串,求出现频率最大的前n项字符串。
//hash映射保存,有string保存字符串,freq保存出现的次数。
//小堆heap以freq为关键值比较,求的前n项大的字符串并且输出。
using namespace std;
struct SNode
{
string str;
SNode *next;
int freq;
SNode(string _s=""):str(_s),freq(0),next(NULL){}
bool operator > (const SNode &snode)
{
return freq>snode.freq;
}
};
struct MyNode
{
SNode *adj;
int count;
MyNode():adj(NULL),count(0){}
};

class Hash
{
friend class Heap;
public:
Hash():node(new MyNode[DefaultSize]){}
int hash(string s)
{
int count = 0;
int n = s.size();
for(int i=0;i<n;i++)
{
count=count*10+s[i]-'0';
}
return count%DefaultSize;
}
void Insert(vector<string> vpt)
{
int n = vpt.size();
for(int i=0;i<n;++i)
{
int index = hash(vpt[i]);
node[index].count++;
if(node[index].adj==NULL)
{
SNode *s = new SNode(vpt[i]);
s->freq++;
node[index].adj = s;
continue;
}
else
{
SNode *p = node[index].adj;

while(p->next!=NULL && p->str!=vpt[i])
{
p = p->next;
}
if(p->str==vpt[i])
{
p->freq++;
continue;
}
else
{
SNode *s = new SNode(vpt[i]);
s->freq++;
p->next = s;
}
}
}
}
void Printf()
{
SNode *p = NULL;
for(int i=0;i<DefaultSize;++i)
{
cout<<node[i].count<<"  :  ";
if(node[i].count!=0)
{
p = node[i].adj;
while(p!=NULL)
{
cout<<(p->str).c_str()<<" ";
p=p->next;
}
}
cout<<endl;
}
}
private:
MyNode *node;
};

void Init(vector<string> &vpt,int n,int length)
{
int i = 0;
string temp;
int m;
while(i<n)
{
m = length;
while(m--)
{
temp+=(rand()%26+'a');
}
++i;
vpt.push_back(temp);
temp="";
}//此处是构造长度为length的字符串n个,都是随机构造的。
 }

class Heap
{
public:
Heap(int _N,Hash &sh):N(_N),current(0)
{
mnd = sh.node;
sd = new SNode[_N];
}
void DealWith()
{
int i = 0;
SNode *p = NULL;
for(;i<DefaultSize;++i)
{
if(mnd[i].adj!=NULL)
{
p = mnd[i].adj;
while(p!=NULL)
{
if(current<N)
{
sd[current++]=(*p);
int n = current/2;
while(n>=0)
{
Set(sd,n);
--n;
}
}
else
{
if(sd[0].freq<p->freq)
{
sd[0]=(*p);
Set(sd,0);
}
}
p = p->next;
}
}
}
}
void Set(SNode *sd,int n)
{
int i = n;
int j = i*2+1;
while(j<current)
{
if(j+1<current && sd[j]>sd[j+1])
++j;
if(sd[i]>sd[j])
{
SNode temp = sd[i];
sd[i] = sd[j];
sd[j] = temp;
}
i = j;
j = i*2+1;
}
}
void PrintfHeap()
{
int i = 0;
for(;i<N;++i)
{
cout<<sd[i].str.c_str()<<" :times="<<sd[i].freq<<endl;
}
}
private:
SNode *sd;
int N;
MyNode *mnd;
int current;
};

int main()
{
vector<string> vpt;
Init(vpt,10000,2);
Hash sh;
sh.Insert(vpt);
//sh.Printf();
Heap hp(4,sh);
hp.DealWith();
hp.PrintfHeap();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: