-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1743.Restore-the-Array-From-Adjacent-Pairs.java
52 lines (42 loc) · 1.43 KB
/
1743.Restore-the-Array-From-Adjacent-Pairs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// https://leetcode.com/problems/restore-the-array-from-adjacent-pairs/
// algorithms
// Medium (58.94%)
// Total Accepted: 4,570
// Total Submissions: 7,753
class Solution {
public int[] restoreArray(int[][] adjacentPairs) {
Map<Integer, List<Integer>> map = new HashMap<>();
for (int[] p : adjacentPairs) {
List<Integer> tmp1 = map.computeIfAbsent(p[0], k -> new ArrayList<>());
tmp1.add(p[1]);
List<Integer> tmp2 = map.computeIfAbsent(p[1], k -> new ArrayList<>());
tmp2.add(p[0]);
}
int size = map.size();
List<Integer> l = new ArrayList<>(size);
int head = -1, pre = -1;
for (Map.Entry<Integer, List<Integer>> entry : map.entrySet()) {
if (entry.getValue().size() == 1) {
head = entry.getKey();
break;
}
}
for (int i = 0; i < size; i++) {
l.add(head);
int preTmp = head;
List<Integer> tmp = map.get(head);
if (tmp.size() == 1) {
head = tmp.get(0);
} else {
head = tmp.get(0) == pre ? tmp.get(1) : tmp.get(0);
}
pre = preTmp;
}
l.add(head);
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = l.get(i);
}
return res;
}
}