Skip to content

Commit 3a24b47

Browse files
authored
Added Restore the Array From Adjacent Pairs.java
1 parent 68d1e1e commit 3a24b47

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public int[] restoreArray(int[][] adjacentPairs) {
3+
Map<Integer, List<Integer>> map = new HashMap<>();
4+
for (int[] pair : adjacentPairs) {
5+
map.computeIfAbsent(pair[0], k -> new ArrayList<>()).add(pair[1]);
6+
map.computeIfAbsent(pair[1], k -> new ArrayList<>()).add(pair[0]);
7+
}
8+
int head = map.keySet().stream().filter(k -> map.get(k).size() == 1).findFirst().orElse(-1);
9+
Set<Integer> visited = new HashSet<>();
10+
int[] result = new int[map.size()];
11+
int idx = 0;
12+
Queue<Integer> queue = new LinkedList<>();
13+
queue.add(head);
14+
while (!queue.isEmpty()) {
15+
int removed = queue.remove();
16+
if (visited.contains(removed)) {
17+
continue;
18+
}
19+
result[idx++] = removed;
20+
visited.add(removed);
21+
queue.addAll(map.get(removed));
22+
}
23+
return result;
24+
}
25+
}

0 commit comments

Comments
 (0)