题目:
There is an integer array nums
that consists of n
unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums
.
You are given a 2D integer array adjacentPairs
of size n - 1
where each adjacentPairs[i] = [ui, vi]
indicates that the elements ui
and vi
are adjacent in nums
.
It is guaranteed that every adjacent pair of elements nums[i]
and nums[i+1]
will exist in adjacentPairs
, either as [nums[i], nums[i+1]]
or [nums[i+1], nums[i]]
. The pairs can appear in any order.
Return the original array nums
. If there are multiple solutions, return any of them.
Example 1:
Input: adjacentPairs = [[2,1],[3,4],[3,2]] Output: [1,2,3,4] Explanation: This array has all its adjacent pairs in adjacentPairs. Notice that adjacentPairs[i] may not be in left-to-right order.
Example 2:
Input: adjacentPairs = [[4,-2],[1,4],[-3,1]] Output: [-2,4,1,-3] Explanation: There can be negative numbers. Another solution is [-3,1,4,-2], which would also be accepted.
Example 3:
Input: adjacentPairs = [[100000,-100000]] Output: [100000,-100000]
Constraints:
nums.length == n
adjacentPairs.length == n - 1
adjacentPairs[i].length == 2
2 <= n <= 105
-105 <= nums[i], ui, vi <= 105
- There exists some
nums
that hasadjacentPairs
as its pairs.
思路:
本题通过率超过65%,在medium里面还是挺高的。最重要的思路是要知道首尾两个元素一定只有一个相邻的数字。因为不在乎首尾顺序,只要找到两个里的任意一个,放到答案数组的头上,然后就可以依次往下计算了。首先将所有数字存入哈希map,形式为<int, vector<int>>,key是数字,value是相邻的一个或者两个数字,这里用pair也可以。然后遍历哈希表,找出只有一个相邻的数字,记录完以后直接break出来。将找出来的数字放在答案数组的第一个,然后将它的相邻数字(只有一个),放在答案数组的第二个,开始循环,对于答案数组中的i来说,只要它是i-1的相邻,那么在哈希表中找到i-1相邻的两个数,其中一个是i-2对应的数,另一个便应该是i在答案数组中对应的数。这样循环最终填满整个数组。
代码:
class Solution {
public:
vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {
unordered_map<int, vector<int>> record;
for (auto &adj : adjacentPairs) {
record[adj[0]].push_back(adj[1]);
record[adj[1]].push_back(adj[0]);
}
int start = -1;
int n = record.size();
for (auto &r:record) {
if(r.second.size()==1) {
start = r.first;
break;
}
}
vector<int> res(n);
res[0] = start;
res[1] = record[start][0];
for(int i = 2; i < n; i++) {
auto &tmp = record[res[i-1]];
res[i] = res[i-2] == tmp[0] ? tmp[1] : tmp[0];
}
return res;
}
};