作者VivianAnn (薇薇安安)
看板Python
标题[问题] leetcode 2029 (Hard) 的问题
时间Mon Nov 29 05:58:49 2021
不知这里有没有高手有参加这周的Leetcode 周赛,想请教leetcode 2029
https://leetcode.com/problems/find-all-people-with-secret/
这题我是用Union-Find来做的,思路大致是:
先用一个dictionary把同一个时间的meeting放在一起,然後由时间小的loop到时间大的
如果该meeting中的参与人x, y中有一个和firstPerson是同一个根节点,则union
在每一个union操作後,将x, y皆放入res
同个时间若有多个meeting,则用一个while loop,不断检查该时间的所有x, y组合
直至res不再变动
以下是我的code,我一直想不透错在哪,到第38个test case时fail了
class Solution(object):
def findAllPeople(self, n, meetings, firstPerson):
"""
:type n: int
:type meetings: List[List[int]]
:type firstPerson: int
:rtype: List[int]
"""
parent = {i: i for i in range(n)}
res = set()
res.add(0)
res.add(firstPerson)
def find(x):
if x != parent[x]:
parent[x] = find(parent[x])
return parent[x]
def union(a, b):
pa, pb = find(a), find(b)
if pa!=pb:
parent[pa] = pb
union(0, firstPerson)
hmap = collections.defaultdict(list)
for a, b, time in meetings:
hmap[time].append((a, b))
for time in sorted(hmap.keys()):
arr = hmap[time]
while True:
tmp = res
for a, b in arr:
if find(a) == find(firstPerson) or find(b) ==
find(firstPerson):
union(a,b)
res.add(a)
res.add(b)
if tmp == res:
break
return list(res)
感谢各位愿意看完
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 108.254.89.199 (美国)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1638136732.A.669.html
1F:推 s0914714: 我猜是find(a) == find(firstPerson) or find(b)...这行 11/29 08:38
2F:→ s0914714: 有可能迭代还没完成但是tmp等於res 11/29 08:38
3F:推 s0914714: 我是用一个set纪录find(a), find(b)跟find(firstPerson) 11/29 09:25
4F:→ s0914714: 每次循环结束检查set长度,如果没变就能跳出 11/29 09:27
5F:→ VivianAnn: 问下,有可能迭代没完成但res = tmp 吗? 11/29 09:33
6F:推 s0914714: 後来find的节点有机会让之前find过的节点变更parent 11/29 09:33
7F:→ s0914714: 最简单的方式就是你的while True改成count跑个5次试试 11/29 09:34
8F:推 s0914714: 不要tmp == res就break 11/29 09:37
9F:→ VivianAnn: 查出问题了,tmp = res.copy()才对,不过会TLE 11/29 09:48
10F:推 s0914714: 都忘了set也是浅拷贝XD 11/29 09:58
11F:→ s0914714: 你的res会越来越大 TLE很正常吧 11/29 10:00
12F:→ s0914714: 改成记长度之类的 11/29 10:01
13F:推 s0914714: 有可能迭代没完成但res = tmp 吗? =>我想错了 这不可能 11/29 10:09
14F:推 cuteSquirrel: 提示: 同一个时段举行的meeting仍然会泄漏秘密 11/29 10:36
15F:推 cuteSquirrel: 提供一组测资,帮助你用来除错。 11/29 10:43
18F:推 s0914714: 不过原PO会把答案加到res 後面的人知道秘密就会加入res 11/29 10:50
19F:→ s0914714: 所以res就跟一开始不一样 11/29 10:50
20F:→ VivianAnn: 谢谢,我已经懂了 11/29 12:39
21F:→ VivianAnn: 这题蛮好的,值得一做 11/29 12:55