leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1743.cpp (744B)


      1 class Solution {
      2   public:
      3     vector<int> restoreArray(const vector<vector<int>> &adjacentPairs) {
      4         const int n = adjacentPairs.size() + 1;
      5         unordered_map<int, vector<int>> um;
      6 
      7         for (const auto &p : adjacentPairs) {
      8             um[p[0]].push_back(p[1]);
      9             um[p[1]].push_back(p[0]);
     10         }
     11 
     12         int start = -1;
     13         for (const auto &[k, v] : um) {
     14             if (v.size() == 1) {
     15                 start = k;
     16                 break;
     17             }
     18         }
     19 
     20         vector<int> res(n);
     21         res[0] = start, res[1] = um[start][0];
     22         for (int i = 2; i < n; i++) {
     23             res[i] = um[res[i - 1]][0] != res[i - 2] ? um[res[i - 1]][0] : um[res[i - 1]][1];
     24         }
     25         return res;
     26     }
     27 };