[问题] leetcode 2029 (Hard) 的问题

楼主: VivianAnn (薇薇安安)   2021-11-29 05:58:49
不知这里有没有高手有参加这周的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)
感谢各位愿意看完
作者: s0914714 (YA)   2021-11-29 08:38:00
我猜是find(a) == find(firstPerson) or find(b)...这行有可能迭代还没完成但是tmp等于res我是用一个set纪录find(a), find(b)跟find(firstPerson)每次循环结束检查set长度,如果没变就能跳出
楼主: VivianAnn (薇薇安安)   2021-11-29 09:33:00
问下,有可能迭代没完成但res = tmp 吗?
作者: s0914714 (YA)   2021-11-29 09:33:00
后来find的节点有机会让之前find过的节点变更parent最简单的方式就是你的while True改成count跑个5次试试不要tmp == res就break
楼主: VivianAnn (薇薇安安)   2021-11-29 09:48:00
查出问题了,tmp = res.copy()才对,不过会TLE
作者: s0914714 (YA)   2021-11-29 09:58:00
都忘了set也是浅拷贝XD你的res会越来越大 TLE很正常吧改成记长度之类的有可能迭代没完成但res = tmp 吗? =>我想错了 这不可能
作者: cuteSquirrel (松鼠)   2021-11-29 10:36:00
提示: 同一个时段举行的meeting仍然会泄漏秘密提供一组测资,帮助你用来除错。http://codepad.org/RmBe4P91留意这段叙述 https://i.imgur.com/rycNcnU.png
作者: s0914714 (YA)   2021-11-29 10:50:00
不过原PO会把答案加到res 后面的人知道秘密就会加入res所以res就跟一开始不一样
楼主: VivianAnn (薇薇安安)   2021-11-29 12:39:00
谢谢,我已经懂了这题蛮好的,值得一做

Links booklink

Contact Us: admin [ a t ] ucptt.com