我正在解决Restore the Array From Adjacent Pairs - LeetCode,我的 solution 并没有 pass 所有的 test case ,想问一下我的 solution 有什么问题,自己完全找不出来。🤐
Thanks in advance.
class Solution:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
num_to_neighbors = defaultdict(list)
for u, v in adjacentPairs:
num_to_neighbors[u].append(v)
num_to_neighbors[v].append(u)
head, next_num = next((num, neighbors[0]) for num, neighbors in num_to_neighbors.items() if len(neighbors) == 1)
res = [head]
while next_num:
res.append(next_num)
next_num = next((neighbor for neighbor in num_to_neighbors[next_num] if neighbor != res[-2]), None)
return res