最常见的程序员面试题(6)计算最常用的URL地址

一个非常常见的面试/笔试题是,一个大型的互联网公司,每天有很多用户浏览。如果想根据用户浏览的信息记录,来看用户最常选用的浏览路径是什么,怎么办? 假设用户数据已经收集到了一个文件里面,这个文iande格式是这样的:
(1)文件是文本文件,共若干行
(2)每一行的格式都相同,例如"用户ID字符串 网址". 在用户ID字符串和网址之间可能有多个空格或者tab。用户ID可能是数字或者非数字
(3)每个用户浏览都必须经过N层地址,例如<home>/<business>/<product>
        那么如何统计? 显然要用到Hash表。用C++和Java分别实现:
  1. //   
  2. // 1. 从文件读取内容并构造dp   
  3. // 2. 遍历dp来构造每个用户id对应的url的地址,这是一个map<strId,urlParts>   
  4. // 3. 当用户id的某个n部分地址构造完成的时候,写入url地址map<strId,count>   
  5. //   3.1 如果set中不存在,创建一个   
  6. //   3.2 如果set中已经存在了,对应计数+1   
  7. // 4. 从set插入到一个排序的map当中   
  8. // 5. 取出map的前N个元素就是所求   
  9. //   
  10. #include<algorithm>   
  11. #include<deque>   
  12. #include<fstream>   
  13. #include<map>   
  14. #include<string>   
  15. #include<sstream>   
  16. #include<unordered_map>   
  17. #include<unordered_set>   
  18. using namespace std;  
  19. typedef pair<const string*,string*> line;  
  20. deque<line> dp;  
  21. struct urlParts{  
  22.     string* part1;  
  23.     string* part2;  
  24.     urlParts(string* p1,string* p2):  
  25.         part1(p1),  
  26.         part2(p2){}  
  27. };  
  28. void find_n_best(size_t nBest)//选择n个最多访问次数   
  29. {  
  30.     struct strHash{  
  31.         size_t operator()(const string* str) const{  
  32.             return std::hash<string>()(*str);  
  33.         }  
  34.     };  
  35.     struct strComp{  
  36.         bool operator()(const string* p1,const string*p2) const{  
  37.             return *p1==*p2;  
  38.         }  
  39.     };  
  40.     unordered_map<string*,urlParts,strHash,strComp> idMap;  
  41.     unordered_map<string*,size_t,strHash,strComp> resultMap;  
  42.     for_each(dp.begin(),dp.end(),[&](const line& li){  
  43.         string* id=const_cast<string*>(li.first);  
  44.         auto it=idMap.find(id);  
  45.         if(it== idMap.end()){//没有找到,创建一个,作为1stPart   
  46.             idMap.insert(make_pair(id,urlParts(li.second,nullptr)));  
  47.         }else{//找到了,看看2ndPart有没有   
  48.             if(it->second.part2==nullptr){  
  49.                 it->second.part2=li.second;  
  50.             }else{//已经有了3部分的url了   
  51.                 string* part1=it->second.part1;  
  52.                 string* part2=it->second.part2;  
  53.                 string* part3=li.second;  
  54.                 string* address=new string(*part1+'/'+*part2+'/'+*part3);  
  55.                 auto fi=resultMap.find(address);  
  56.                 if(fi==resultMap.end()){  
  57.                     resultMap.insert(make_pair(address,1));  
  58.                 }else{//计数已经存在了   
  59.                     ++(fi->second);  
  60.                 }  
  61.             }  
  62.         }  
  63.     });  
  64.   
  65.     struct f{  
  66.         bool operator()(const size_t n1,const size_t n2) const  
  67.         {  
  68.             return n1>n2;  
  69.         }  
  70.     };  
  71.     map<size_t,string*,f> map2Sort;  
  72.     for_each(resultMap.begin(),resultMap.end(),  
  73.             [&](const pair<const string*,size_t>& p){  
  74.                 const size_t n=p.second;  
  75.                 string* ps=const_cast<string*>(p.first);  
  76.                 map2Sort.insert(make_pair(n,ps));  
  77.     });  
  78.       
  79.     for(auto it=map2Sort.begin();it!=map2Sort.end();++it){  
  80.         printf("count=%d,url=%s\n",it->first,it->second->c_str());  
  81.         if(!(--nBest))break;  
  82.     }  
  83.     for_each(resultMap.begin(),resultMap.end(),[](pair<const string*,size_t> p)  
  84.     {  
  85.         delete p.first;  
  86.     });  
  87. }  
  88. int main(void){  
  89.     ifstream fs(_T("d:\\url.txt"));  
  90.     if(!fs.is_open()){  
  91.         printf("open failed:%d\n",fs.fail());  
  92.         return 1;  
  93.     }  
  94.     int count=0;  
  95.     string sLine;  
  96.     stringstream ss;  
  97.     while(getline(fs,sLine)){  
  98.         string* pId=new string;  
  99.         string* pUrl=new string;  
  100.         ss.clear();  
  101.         ss<<sLine;  
  102.         ss>>*pId;  
  103.         ss>>*pUrl;  
  104.         if(pUrl->empty()){  
  105.             printf("%d\n",count);  
  106.         }  
  107.         dp.push_back(make_pair(pId,pUrl));  
  108.         ++count;  
  109.     }  
  110.     find_n_best(3);  
  111.     fs.close();  
  112.     for_each(dp.begin(),dp.end(),[](line li){  
  113.         delete li.first;  
  114.         delete li.second;  
  115.     });  
  116.     return 0;  
  117. }  
//
// 1. 从文件读取内容并构造dp
// 2. 遍历dp来构造每个用户id对应的url的地址,这是一个map<strId,urlParts>
// 3. 当用户id的某个n部分地址构造完成的时候,写入url地址map<strId,count>
//   3.1 如果set中不存在,创建一个
//   3.2 如果set中已经存在了,对应计数+1
// 4. 从set插入到一个排序的map当中
// 5. 取出map的前N个元素就是所求
//
#include<algorithm>
#include<deque>
#include<fstream>
#include<map>
#include<string>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
using namespace std;
typedef pair<const string*,string*> line;
deque<line> dp;
struct urlParts{
	string* part1;
	string* part2;
	urlParts(string* p1,string* p2):
		part1(p1),
		part2(p2){}
};
void find_n_best(size_t nBest)//选择n个最多访问次数
{
	struct strHash{
		size_t operator()(const string* str) const{
			return std::hash<string>()(*str);
		}
	};
	struct strComp{
		bool operator()(const string* p1,const string*p2) const{
			return *p1==*p2;
		}
	};
	unordered_map<string*,urlParts,strHash,strComp> idMap;
	unordered_map<string*,size_t,strHash,strComp> resultMap;
	for_each(dp.begin(),dp.end(),[&](const line& li){
		string* id=const_cast<string*>(li.first);
		auto it=idMap.find(id);
		if(it== idMap.end()){//没有找到,创建一个,作为1stPart
			idMap.insert(make_pair(id,urlParts(li.second,nullptr)));
		}else{//找到了,看看2ndPart有没有
			if(it->second.part2==nullptr){
				it->second.part2=li.second;
			}else{//已经有了3部分的url了
				string* part1=it->second.part1;
				string* part2=it->second.part2;
				string* part3=li.second;
				string* address=new string(*part1+'/'+*part2+'/'+*part3);
				auto fi=resultMap.find(address);
				if(fi==resultMap.end()){
					resultMap.insert(make_pair(address,1));
				}else{//计数已经存在了
					++(fi->second);
				}
			}
		}
	});

	struct f{
		bool operator()(const size_t n1,const size_t n2) const
		{
			return n1>n2;
		}
	};
	map<size_t,string*,f> map2Sort;
	for_each(resultMap.begin(),resultMap.end(),
		    [&](const pair<const string*,size_t>& p){
				const size_t n=p.second;
				string* ps=const_cast<string*>(p.first);
				map2Sort.insert(make_pair(n,ps));
	});
	
	for(auto it=map2Sort.begin();it!=map2Sort.end();++it){
		printf("count=%d,url=%s\n",it->first,it->second->c_str());
		if(!(--nBest))break;
	}
	for_each(resultMap.begin(),resultMap.end(),[](pair<const string*,size_t> p)
	{
		delete p.first;
	});
}
int main(void){
	ifstream fs(_T("d:\\url.txt"));
	if(!fs.is_open()){
		printf("open failed:%d\n",fs.fail());
		return 1;
	}
	int count=0;
	string sLine;
	stringstream ss;
	while(getline(fs,sLine)){
		string* pId=new string;
		string* pUrl=new string;
		ss.clear();
		ss<<sLine;
		ss>>*pId;
		ss>>*pUrl;
		if(pUrl->empty()){
			printf("%d\n",count);
		}
		dp.push_back(make_pair(pId,pUrl));
		++count;
	}
	find_n_best(3);
	fs.close();
	for_each(dp.begin(),dp.end(),[](line li){
		delete li.first;
		delete li.second;
	});
	return 0;
}
        OK, 上面这个C++的程序稍烦了一点,因为我先读完了文件再集中进行处理。我们也可以边读边处理。Java的ConcurrentHashMap提供了更加强大和方便的功能来做这样一件事情,构造和查找比C++更方便一点:
  1. import java.io.*;  
  2. import java.util.*;  
  3. import java.util.concurrent.*;  
  4. public class BestURL{  
  5.     static class urlParts{  
  6.         String sPart1;  
  7.         String sPart2;  
  8.     }  
  9.     public static void main(String[] args) {  
  10.         ConcurrentHashMap<String,urlParts> dp=new ConcurrentHashMap<String,urlParts>();  
  11.         ConcurrentHashMap<String,Integer> result=new ConcurrentHashMap<String,Integer>();    
  12.         try{  
  13.             FileInputStream is=new FileInputStream("d:\\my.txt");  
  14.             Scanner scan=new Scanner(is);  
  15.             while(scan.hasNext()){  
  16.                 String s=scan.nextLine();  
  17.                 if(s.isEmpty())break;  
  18.                 StringTokenizer t=new StringTokenizer(s," ");  
  19.                 String key=t.nextToken();  //用户ID   
  20.                 String value=t.nextToken();//用户访问的页面名称   
  21.                 System.out.println(key+","+value);  
  22.                   
  23.                 //对于每一行记录   
  24.                 if(!dp.containsKey(key)){  
  25.                     urlParts parts=new urlParts();  
  26.                     parts.sPart1=value;  
  27.                     dp.put(key, parts);  
  28.                 }else{  
  29.                     urlParts parts=dp.get(key);  
  30.                     if(parts.sPart2==null){  
  31.                         parts.sPart2=value;  
  32.                     }else{  
  33.                         //已经有了前面两部分的内容了   
  34.                         String address=parts.sPart1+'/'+parts.sPart2+'/'+value;  
  35.                         if(!result.containsKey(address)){  
  36.                             result.put(address, 1);  
  37.                         }else{  
  38.                             Integer i=result.get(address);  
  39.                             i+=1;  
  40.                             result.put(address, i);  
  41.                         }  
  42.                         dp.remove(key);  
  43.                     }  
  44.                 }  
  45.             }  
  46.         }catch(FileNotFoundException e){  
  47.             e.printStackTrace();  
  48.         }  
  49.         class MyComp implements Comparator<Integer>{  
  50.             public int compare(Integer i1, Integer i2){  
  51.                 int v1=i1.intValue();  
  52.                 int v2=i2.intValue();  
  53.                 return (v1>v2? -1:(v1==v2?0:1));  
  54.             }  
  55.         }  
  56.         TreeMap<Integer,String> sorted=new TreeMap<Integer,String>(new MyComp());  
  57.         Set<String> resultSet=result.keySet();  
  58.         for(Iterator<String> it=resultSet.iterator();it.hasNext();){  
  59.             String sKey=(String)it.next();  
  60.             Integer count=result.get(sKey);  
  61.             sorted.put(count, sKey);  
  62.         }//sorted是排好序的   
  63.         Set<Integer> sortedSet=sorted.keySet();  
  64.         for(Iterator<Integer> it=sortedSet.iterator();it.hasNext();){  
  65.             Integer key=(Integer)it.next();  
  66.             String add=sorted.get(key);  
  67.             System.out.println("count="+key.intValue()+",address="+add);  
  68.         }  
  69.     }  
  70. }  
  71. <SPAN style="FONT-FAMILY: Arial; BACKGROUND-COLOR: #ffffff"></SPAN>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值