684-Redundant Connection
Description
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.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
1
/ \
2 - 3
Example 2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
| |
4 - 3
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.
問題描述
在這個問題中, 樹是沒有環的連通的無向圖
給定的輸入為有N個節點(值互不相同, 1, 2, …N)的樹, 其中有一條邊是多餘的。多餘的邊不是已有的邊。
圖的邊由二維陣列給出。每條邊為[u, v], 其中u < v, 表示u到v的無向邊
返回多餘的邊, 使得移除這條邊後, 剩下的圖為一個有N個節點的樹。若存在多個解, 返回二維陣列中的最後一個。
返回的邊同樣以[u, v]的形式表示, u < v.
問題分析
使用dfs或者並查集來做
若加入一條邊之前, 該邊的兩個頂點已經連通, 那麼這條邊即為結果。否則, 將這條邊新增到圖中(若以並查集來做, 就是union)
解法1(dfs)
class Solution {
Set<Integer> seen = new HashSet();
int MAX_EDGE_VAL = 1000;
public int[] findRedundantConnection(int[][] edges) {
ArrayList<Integer>[] graph = new ArrayList[MAX_EDGE_VAL + 1];
for (int i = 0; i <= MAX_EDGE_VAL; i++) {
graph[i] = new ArrayList();
}
for (int[] edge: edges) {
seen.clear();
if (!graph[edge[0]].isEmpty() && !graph[edge[1]].isEmpty() &&
dfs(graph, edge[0], edge[1])) {
return edge;
}
graph[edge[0]].add(edge[1]);
graph[edge[1]].add(edge[0]);
}
throw new AssertionError();
}
//判斷source和target是否連通
public boolean dfs(ArrayList<Integer>[] graph, int source, int target) {
if (!seen.contains(source)) {
seen.add(source);
if (source == target) return true;
for (int nei: graph[source]) {
if (dfs(graph, nei, target)) return true;
}
}
return false;
}
解法2(並查集)
class Solution {
public int[] findRedundantConnection(int[][] edges) {
// max size 1000, num from 1 to 1000
int[] parent = new int[1001];
for(int[] edge: edges){
int a = find(parent, edge[0]);
int b = find(parent, edge[1]);
if(a == b) return edge;
// union
parent[b] = a;
}
return new int[2];
}
private int find(int[] parent, int f) {
if(parent[f] == 0){
parent[f] = f;
return f;
}
while(f != parent[f]){
// path compression
parent[f] = parent[parent[f]];
f = parent[f];
}
return f;
}
}
相關文章
- nacos Connection refused (Connection refused)
- Connection
- java.net.ConnectException: Connection refused (Connection refused)JavaException
- Error:Can't connect to SOCKS proxy:Connection refused (Connection refused)Error
- nmcli connection reload
- yarn socket connection timeoutYarn
- 關於Residual Connection
- Connection could not be established with host 求救
- Check connection related issue of mysqlMySql
- ascp: Failed to open TCP connection for SSH, exiting. Session Stop (Error: Failed to open TCP connection for SSH)AITCPSessionError
- MySQL異常刨析:ata source rejected establishment of connection, message from server: “Too many connectionMySqlServer
- MySQL:Lost connection to MySQL server at 'readingMySqlServer
- Dr.Elephant mysql connection errorMySqlError
- OGG Director報錯 Connection FAILEDAI
- [20190530]sqlplus preliminary connection.txtSQL
- Please specify (single) host string for connection:
- go get報錯connect: connection refusedGo
- 如何區分 Connection、Thread和SessionthreadSession
- [network][easy case]troubleshoting the connection to a remote serverREMServer
- SQLServer映象報錯Connection handshake failedSQLServerAI
- Lost connection to MySQL server at 'reading authorization packet'MySqlServer
- Error: Connection activation failed: Device not managed by NetworkManagerErrorAIdev
- Leetcode 685. Redundant Connection II JavascriptLeetCodeJavaScript
- SSL - SSLHandshakeException: Unrecognized SSL message, plaintext connection?ExceptionZedAI
- SSH出現Connection refused錯誤
- 阿里雲站點升級提示:OpenSSL SSL_connect: Connection reset by peer in connection to www.pbootcms.com:443阿里boot
- Mysql 如何更改default collation_connection settingMySql
- no declaration can be found for element rabbit:connection-factory
- lightdb WARNING: could not establish connection after 30000 ms
- nameko shell 報錯 : [Errno 111] Connection refused
- Failed to get D-Bus connection: Operation not permittedAIMIT
- raw.githubusercontent.com port 443: Connection refusedGithub
- Error!: SQLSTATE[HY000] [2002] Connection refusedErrorSQL
- ‘OpenSSL SSL_read: Connection was reset, errno 10054’
- java.net.ConnectException: Connection refused 異常JavaException
- ssh: connect to host localhost port 22: Connection refusedlocalhost
- Linux啟動tomcat後執行shutdown.sh關閉時出現異常:Connection refused (Connection refused)LinuxTomcat
- NOClassDefFoundError org.springframework.data.redis.connection.zset.tupleErrorSpringFrameworkRedis