其他分享
首页 > 其他分享> > Leetcode 5665: 从相邻元素对还原数组

Leetcode 5665: 从相邻元素对还原数组

作者:互联网

题目描述

存在一个由 n 个不同元素组成的整数数组 nums ,但你已经记不清具体内容。好在你还记得 nums 中的每一对相邻元素。

给你一个二维整数数组 adjacentPairs ,大小为 n - 1 ,其中每个 adjacentPairs[i] = [ui, vi] 表示元素 ui 和 vi 在 nums 中相邻。

题目数据保证所有由元素 nums[i] 和 nums[i+1] 组成的相邻元素对都存在于 adjacentPairs 中,存在形式可能是 [nums[i], nums[i+1]] ,也可能是 [nums[i+1], nums[i]] 。这些相邻元素对可以 按任意顺序 出现。

返回 原始数组 nums 。如果存在多种解答,返回 其中任意一个 即可。

 

示例 1:

输入:adjacentPairs = [[2,1],[3,4],[3,2]]
输出:[1,2,3,4]
解释:数组的所有相邻元素对都在 adjacentPairs 中。
特别要注意的是,adjacentPairs[i] 只表示两个元素相邻,并不保证其 左-右 顺序。
示例 2:

输入:adjacentPairs = [[4,-2],[1,4],[-3,1]]
输出:[-2,4,1,-3]
解释:数组中可能存在负数。
另一种解答是 [-3,1,4,-2] ,也会被视作正确答案。
示例 3:

输入:adjacentPairs = [[100000,-100000]]
输出:[100000,-100000]
 

提示:

nums.length == n
adjacentPairs.length == n - 1
adjacentPairs[i].length == 2
2 <= n <= 105
-105 <= nums[i], ui, vi <= 105
题目数据保证存在一些以 adjacentPairs 作为元素对的数组 nums

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-the-array-from-adjacent-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

解题思路

class Solution {
public:
    void dfs(int u, unordered_map<int, vector<int>> &graph, unordered_map<int, int> &vis, vector<int> &ans){
        vis[u] = 1;
        ans.push_back(u);
        for(int i = 0; i < graph[u].size(); i++){
            int v = graph[u][i];
            if(vis[v] == 0) dfs(v, graph, vis, ans);
        }
    }

    vector<int> restoreArray(vector<vector<int>>& adjacentPairs) {
        vector<int> ans;
        unordered_map<int, vector<int>> graph;
        unordered_map<int, int> vis;
        for(auto &it : adjacentPairs){
            int u = it[0];
            int v = it[1];
            graph[u].push_back(v);
            graph[v].push_back(u);
            vis[u] = 0;
            vis[v] = 0;
        }
        int start = 0;
        for(auto &it : graph){
            if(it.second.size() == 1) start = it.first;
        }
        dfs(start, graph, vis, ans);
        return ans;
    }
};

 

标签:5665,nums,int,graph,vis,adjacentPairs,数组,ans,Leetcode
来源: https://blog.csdn.net/weixin_35338624/article/details/113470160