腾讯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; }
相关文章推荐
- 作为程序员,你最害怕的是什么?
- 程序员经常说的30句话,吐槽吧程序员!
- 一道博弈的面试题及其算法正确性证明
- 转自百度上一位大龄程序员的肺腑之言
- 开始记录我的程序员学习生涯--小小的我,也有大大的梦想;
- 黑马程序员——多线程
- 面试题总结1
- java多线程面试问题及答案
- 黑马程序员----反射
- 《剑指Offer》面试题:数组中的逆序对的总数
- 1 Two Sum
- IT职场心得
- 黑马程序员——Java基础——面向对象的特征(一)
- 程序员之路(高手的经验之谈)
- 黑马程序员──────Java基础───抽象、接口与文本的建立
- 黑马程序员──────Java基础───继承和多态
- 黑马程序员─────Java基础───字符串
- 黑马程序员——java基础——面向对象
- 黑马程序员_java环境配置
- 黑马程序员——File类