1743. Restore the Array From Adjacent Pairs
Solutions
class Solution {
public:
vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {
// build graph
unordered_map<int, vector<int>> m;
for (auto & e : adjacentPairs) {
m[e[0]].push_back(e[1]);
m[e[1]].push_back(e[0]);
}
// find the head/tail
int st = -1;
for (auto & [cur, adj] : m) {
if (adj.size() == 1) {
st = cur;
break;
}
}
// rebuild the chain from the head/tail
vector<int> res = {st};
int cur = m[st][0];
while (true) {
int back = cur;
for (auto next : m[cur]) {
if (next == res.back()) continue;
cur = next;
}
res.push_back(back);
// didn't extend, reach the other end
if (cur == back) break;
}
return res;
}
};Last updated