coursera算法公开课练习题Interview(1)

来源:互联网 发布:使徒行者2 知乎 编辑:程序博客网 时间:2024/06/06 16:29
  1. Question: Social network connectivity. Given a social network containing n members and a log file containing m timestamps at which times pairs of members formed friendships, design an algorithm to determine the earliest time at which all members are connected (i.e., every member is a friend of a friend of a friend … of a friend). Assume that the log file is sorted by timestamp and that friendship is an equivalence relation. The running time of your algorithm should be mlogn or better and use extra space proportional to n.

    问题描述:上面的问题说的是一个社交网络的动态连接问题,问题描述中是说一共有n名成员和一个包括m个时间戳的log文件(在每个时间戳内两名成员成为了朋友),现在想要知道在什么时间戳结束后所有的成员都成为了好朋友,即所有的节点连通了。要求运行时间是mlogn以下,空间是和n成比例的。

    解决方案:数据结构采用压缩路径且带权值的quick-union,将log文件抽象成有序数组,数组中的对象是将要连通的两个分量以及一个时间戳,在union操作里面参数是数组中的对象,并加入对于count即组件数的判定,当count等于1的时候,打印出此时输入对象的时间戳分量。

  2. Question: Union-find with specific canonical element. Add a method find() to the union-find data type so that find(i) returns the largest element in the connected component containing i. The operations, union(), connected(), and find() should all take logarithmic time or better.
    For example, if one of the connected components is {1,2,6,9}, then the find() method should return 9 for each of the four elements in the connected components.

    问题描述:带有特定的规范元素的Union-find。 向union-find数据类型添加一个方法find(),以便find(i)返回包含i的连接组件中的最大元素。union(),connected()和find() 操作都应该取对数时间或更好。
    例如,如果一个连接的组件是{1,2,6,9},那么find()方法应该为每一个组件中连接的四个元素返回9。

    解决方案:数据结构采用带权值的quick-union,这里我的理解是添加一个返回组件中最大元素的方法,并不改变原有的find()方法(可能错了:D),可以添加一个整型数组max,在union操作的时候改变p、q的根节点在max数组相应索引位置中的值,再添加一个getMax()方法,返回p的根节点所在max数组中相应索引位置的值。

  3. Question: Successor with delete. Given a set of N integers S={0,1,…,N−1} and a sequence of requests of the following form:

    • Remove x from S
    • Find the successor of x: the smallest y in S such that y≥x.
    Design a data type so that all operations (except construction) should take logarithmic time or better.

    问题描述: 这里给了一系列的整数,要求实现这样的一种数据结构:1.可以删除元素;2.可以针对x找到在集合里面的不小于x的最小元素。

    解决方案: 这个问题其实是上一个问题的应用,具体来说的话,我们要删除一个元素x,再找到x的下一个元素。这里将x在数组中的索引先假设是i,那么找下一个元素可以看做是先进行操作union(array[i], array[i+1]),然后找到x所在集合的最大值。但针对x有没有被删除可以添加一个boolean数组来进行判定。

0 0
原创粉丝点击