• 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目2


    2014-04-24 20:44

    题目:对于Facebook、Linkedin这样的社交网站,你要如何设计一个数据结构来表示用户之间的关系呢?比如两个用户互为2nd-degree connection。你要如何设计算法来找出他们之间的联系路径呢?

    解法:显然,社交网络的数据是平方级别的,因为任何人的联系往往是C(n, 2) = n * (n - 1) / 2。所以这种数据结构应该是个无向图和有向图的结合。人脉之间是互相建立的,所以是无向图,而“Follow”行为是单向的,所以应该为有向图。如果要发掘两个用户间的人脉路径,广度优先搜索肯定是最简单直白的。单向或是双向广搜可能效率上有一定差别,但对于这样的大型网站肯定都不行,因为响应时间要求很高。如果用空间换取时间,用动态规划的思想,把一度人脉、二度人脉逐层计算并保存下来,这样就能避免重复计算了。算法分为在线和离线两种设计,这样开销巨大的搜索过程,就应该以合理的间隔进行离线计算,保证在线查询的高效响应。如果你问:“我的人脉情况会变化,这样显示出来的结果岂不是错的?”那么我说,下次重新计算的时候,就会对了,你对错误的容忍程度决定了下次服务器重新计算人脉的时间间隔。

    代码:

     1 // 10.2 Describe how you would design the data structure for people in social network. How would you determine the degree of connections between two people.
     2 // Answer:
     3 // Appartently social network involves a lot of graph thoery. It describes the connections between people.
     4 class Person {
     5     // A lot of data 
     6     vector<Person *> friends;
     7 };
     8 // Basically every people is a node in the grap.
     9 // For two people, if you want to find out through how many people they're connected, BFS may be a practical way.
    10 // But it's not effiecient enough, double-end BFS will be a little better.
    11 // You may record the list of 2nd degree connections, so you can retrieve 3rd degree connections faster.
    12 // And you surely wouldn't be interested in 10th degree connections, as anyone on this earth may be your 10th degree connection.
    13 // So it's important to limit the connection search to a small scale of no more than 3rd degree.
    14 int main()
    15 {
    16     return 0;
    17 }
  • 相关阅读:
    SpringData JPA @Query动态SQL语句,且分页
    Springboot项目修改html后不需要重启---springboot项目的热部署
    sqlserver如何进行日期转换
    导入项目时候出现 Description Resource Path Location Type Cannot change version of project facet Dynamic Web Module to 2.5错误
    Intellij IDEA和Eclipse之间的常用快捷键
    Java 集合转换(数组、List、Set、Map相互转换)
    oracle日期格式转换 to_date(),to_char()
    java数据缓存
    VMware14安装Centos8详细教程图解教程
    CentOS7 安装Xfce桌面环境
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3687364.html
Copyright © 2020-2023  润新知