1. 解题思路
这一题思路上的话就是一个最短路径的求解问题,我们使用一个堆排即可对其进行实现。
不过,做题的时候挺犹豫的,因为感觉要对每一条路径保留下其历史路径,这个无论是计算开销还是存储开销都挺大的,感觉还是挺暴力的,没想到还真的成功了,也有点意外……
2. 代码实现
给出python代码实现如下:
class Solution:
def findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]:
graph = defaultdict(list)
for i, (u, v, w) in enumerate(edges):
graph[u].append((v, w, i))
graph[v].append((u, w, i))
ans = [False for _ in edges]
distances = [math.inf for _ in range(n)]
q = [(0, 0, [])]
while q != []:
dis, u, edges = heapq.heappop(q)
if dis > distances[u]:
continue
distances[u] = dis
for v, w, e in graph[u]:
if dis + w <= distances[v]:
heapq.heappush(q, (dis+w, v, edges + [e]))
if u == n-1:
for e in edges:
ans[e] = True
return ans
提交代码评测得到:耗时1911ms,占用内存50.8MB。
本文介绍了如何使用堆数据结构解决LeetCode题目3123,通过暴力搜索找到在最短路径中的边。作者分享了解题思路和Python代码实现,时间复杂度1911ms,内存占用50.8MB。
202

被折叠的 条评论
为什么被折叠?



