查看: 747| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

[高频题] Match users with other teams

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
题目是:

You are given a list of users with name and team they belong to. Now you have to match every user to one other user randomly so that they can get to know each other. User match should be from different team. Find out the maximum possible match. If list size is odd then you can ignore one user.

Example - Input - [["Alex","Infra"],["Kevin","Search"],["Jill","HR"],["Jane","Infra"],["Justin","Search"],["Michael","HR"]]

Output - [["Alex","Justin"],["Kevin","Jill"],["Jane","Michael"]]

We dont want  ["Alex","Justin"] and ["Jane","Kevin"] combination. In that case we will left with 2 members from team HR so we are wasting 2 members here.

按组放进dictionary,然后用max heap排序,每次抽取前两个组match,把剩下的放回heap,但总是会漏到一些case。

大神能给个提示吗


补充内容 (2021-08-29 10:27 +8:00):
做出来了:

思路还是是按组放进dictionary,然后用max heap排序,每次抽取前两个组match(之前是尽可能最大match数量,现在只match 1 组),把剩下的放回heap。

请问大神们有建议吗?

上一篇:由104. Maximum depth of binary tree引申的关于global result和self.result的疑问
下一篇:求优化,最后一个test case过不去!【FB Coding Puzzle】
🔗
S03S 2021-10-6 04:44:19 | 只看该作者
全局:
本帖最后由 S03S 于 2021-10-5 16:46 编辑

python , 大神指点下:
···

  1. <div class="blockcode"><blockquote>def match_team(members):
  2.     hq = []
  3.     team_members = collections.defaultdict(list)
  4.     for mem, team in members:
  5.         team_members[team].append(mem)
  6.     for team, members in team_members.items():
  7.         heapq.heappush(hq, (-len(members), team, members))
  8.     res = []
  9.     while len(hq) >= 2:
  10.         print(hq)
  11.         a_len, a_team, a_members = heapq.heappop(hq)
  12.         b_len, b_team, b_members = heapq.heappop(hq)
  13.         res.append((a_members.pop(), b_members.pop()))
  14.         if a_len < -1:
  15.             heapq.heappush(hq, (a_len+1, a_team, a_members))
  16.         if b_len < -1:
  17.             heapq.heappush(hq, (b_len+1, b_team, b_members))
  18.     return res

  19. input = [["Alex","Infra"],["Kevin","Search"],["Jill","HR"],["Jane","Infra"],["Justin","Search"],["Michael","HR"]]
  20. print(match_team(input))
复制代码
回复

使用道具 举报

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

本版积分规则

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