存在一个由 n
个不同元素组成的整数数组 nums
,但你已经记不清具体内容。好在你还记得 nums
中的每一对相邻元素。
给你一个二维整数数组 adjacentPairs
,大小为 n - 1
,其中每个 adjacentPairs[i] = [ui, vi]
表示元素 ui
和 vi
在 nums
中相邻。
题目数据保证所有由元素 nums[i]
和 nums[i+1]
组成的相邻元素对都存在于 adjacentPairs
中,存在形式可能是 [nums[i], nums[i+1]]
,也可能是 [nums[i+1], nums[i]]
。这些相邻元素对可以 按任意顺序 出现。
返回 原始数组 nums
。如果存在多种解答,返回 其中任意一个 即可。
示例 1:
输入:adjacentPairs = [[2,1],[3,4],[3,2]] 输出:[1,2,3,4] 解释:数组的所有相邻元素对都在 adjacentPairs 中。 特别要注意的是,adjacentPairs[i] 只表示两个元素相邻,并不保证其 左-右 顺序。
示例 2:
输入:adjacentPairs = [[4,-2],[1,4],[-3,1]] 输出:[-2,4,1,-3] 解释:数组中可能存在负数。 另一种解答是 [-3,1,4,-2] ,也会被视作正确答案。
示例 3:
输入:adjacentPairs = [[100000,-100000]] 输出:[100000,-100000]
提示:
nums.length == n
adjacentPairs.length == n - 1
adjacentPairs[i].length == 2
2 <= n <= 105
-105 <= nums[i], ui, vi <= 105
- 题目数据保证存在一些以
adjacentPairs
作为元素对的数组nums
从度为一的点开始遍历图
class Solution:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
graph = defaultdict(list)
for pair in adjacentPairs:
graph[pair[0]].append(pair[1])
graph[pair[1]].append(pair[0])
ans = []
vis = set()
def dfs(idx):
if idx in vis:
return
vis.add(idx)
ans.append(idx)
for nxt in graph[idx]:
dfs(nxt)
start = -1
for idx, adj in graph.items():
if len(adj) == 1:
start = idx
break
dfs(start)
return ans
class Solution {
public int[] restoreArray(int[][] adjacentPairs) {
Map<Integer, List<Integer>> graph = new HashMap<>();
for (int[] pair : adjacentPairs) {
graph.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
graph.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);
}
List<Integer> ans = new ArrayList<>();
Set<Integer> vis = new HashSet<>();
int start = -1;
for (Map.Entry<Integer, List<Integer>> entry : graph.entrySet()) {
if (entry.getValue().size() == 1) {
start = entry.getKey();
break;
}
}
dfs(graph, ans, vis, start);
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
private void dfs(Map<Integer, List<Integer>> graph, List<Integer> ans, Set<Integer> vis, int idx) {
if (vis.contains(idx)) {
return;
}
vis.add(idx);
ans.add(idx);
for (Integer next : graph.get(idx)) {
dfs(graph, ans, vis, next);
}
}
}
func restoreArray(adjacentPairs [][]int) []int {
graph := make(map[int][]int)
for _, pair := range adjacentPairs {
graph[pair[0]] = append(graph[pair[0]], pair[1])
graph[pair[1]] = append(graph[pair[1]], pair[0])
}
ans := make([]int, 0)
vis := make(map[int]bool)
var start int
for idx, adj := range graph {
if len(adj) == 1 {
start = idx
break
}
}
dfs(graph, &ans, vis, start)
return ans
}
func dfs(graph map[int][]int, ans *[]int, vis map[int]bool, idx int) {
if vis[idx] {
return
}
vis[idx] = true
*ans = append(*ans, idx)
for _, next := range graph[idx] {
dfs(graph, ans, vis, next)
}
}