12
返回列表 发新帖
楼主: 口才张
跳转到指定楼层
上一主题 下一主题
收起左侧

[找工就业] 前两天面试的一道题,想不出来应该用什么方法!求大神解答!

全局:
union find
回复

使用道具 举报

🔗
cecilianxf 2019-8-20 20:14:00 | 只看该作者
全局:
Union find...
以下是一个用uf的例子. From 1point 3acres bbs
  1. # union find. 1point 3 acres
  2.     def initialize(self,accounts):
  3.         self.id_to_email = {}
  4.         self.father = {}-baidu 1point3acres
  5.         for user_id, emails in enumerate(accounts):
  6.             self.father[user_id] = user_id. 1point3acres.com
  7.             self.id_to_email[user_id] = set(emails[1:]).
  8.     def find(self,user_id):
  9.         path = []
  10.         while user_id != self.father[user_id]:
  11.             path.append(user_id)
  12.             user_id = self.father[user_id]
  13.         for n in path:
  14.             self.father[n] = user_id
  15.         return user_id. From 1point 3acres bbs
  16.             
  17.     def union(self,d1, d2):
  18.         root_id1 = self.find(d1)
  19.         root_id2 = self.find(d2)
  20.         if root_id1!= root_id2:. Χ
  21.             self.father[root_id1] = root_id2
  22.             self.id_to_email[root_id2] = self.id_to_email[root_id1].union(self.id_to_email[root_id2])
复制代码
回复

使用道具 举报

🔗
Kayle_Yang 2019-8-21 01:20:50 | 只看该作者
全局:
我觉的如果你想用搜索来做的话 可以参考number of islands
我的想法是 先把他们po进无向图里,把同一个set里的先连起来,然后从A开始跑BFS找所有关联点,期间用hashset来prune去重。
不过最后列表里各个list里元素可能是无序的
回复

使用道具 举报

🔗
 楼主| 口才张 2019-8-21 12:48:31 | 只看该作者
全局:
Kayle_Yang 发表于 2019-8-21 01:20. From 1point 3acres bbs
我觉的如果你想用搜索来做的话 可以参考number of islands
我的想法是 先把他们po进无向图里,把同一个set ...
. check 1point3acres for more.
wow,好有趣的idea
回复

使用道具 举报

🔗
 楼主| 口才张 2019-8-21 12:49:23 | 只看该作者
全局:
cecilianxf 发表于 2019-8-20 20:14. 1point3acres.com
Union find...
以下是一个用uf的例子
[mw_shl_code=python,true] # union find

太感谢了!网上很多template都要重新写个class,这个好棒!
回复

使用道具 举报

🔗
jtzc0123 2019-8-21 13:57:41 | 只看该作者
全局:
标准union find,就是在看你知不知道这个数据结构,你就算用search做出来面试官也觉得不是最优解……
回复

使用道具 举报

🔗
cecilianxf 2019-8-21 19:59:14 | 只看该作者
全局:
口才张 发表于 2019-8-21 12:49
太感谢了!网上很多template都要重新写个class,这个好棒!

这个是account merge那道题的代码(leetcode能搜到)。你把这个写一遍再把account merge那道题的主代码写一下,uf就差不多没问题了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表