684. Redundant Connection(Leetcode每日一題-2021.01.13)--抄答案
技術標籤:leetcode每日一題202101leetcode並查集
Problem
In this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
Note:
- The size of the input 2D-array will be between 3 and 1000.
- Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
Example1
Example2
Solution
class Solution {
public:
vector<int> p;
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
if(edges.empty())
return {};
int N = 0;
for(int i = 0;i<edges.size();++i)
{
int u = edges[i][0];
int v = edges[i][1];
N = max(N,max(u,v));
}
for(int i = 0;i<=N;++i)
p.push_back(i);
for(int i = 0;i<edges.size();++i)
{
int u = edges[i][0];
int v = edges[i][1];
if(find(u) != find(v))
p[find(u)] = find(v);
else
return {u,v};
}
return {};
}
};