Skip to content

Commit 7fe62a0

Browse files
refactor 261
1 parent d49c632 commit 7fe62a0

File tree

1 file changed

+23
-20
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+23
-20
lines changed

src/main/java/com/fishercoder/solutions/_261.java

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
/**
44
*261. Graph Valid Tree
5-
*Given n nodes labeled from 0 to n - 1 and a list of undirected edges
5+
*
6+
* Given n nodes labeled from 0 to n - 1 and a list of undirected edges
67
* (each edge is a pair of nodes),
78
* write a function to check whether these edges make up a valid tree.
89
@@ -24,31 +25,33 @@
2425
*/
2526
public class _261 {
2627

27-
public boolean validTree(int n, int[][] edges) {
28-
int[] nums = new int[n];
29-
for (int i = 0; i < n; i++) {
30-
nums[i] = i;
31-
}
28+
public static class Solution1 {
29+
public boolean validTree(int n, int[][] edges) {
30+
int[] nums = new int[n];
31+
for (int i = 0; i < n; i++) {
32+
nums[i] = i;
33+
}
34+
35+
for (int i = 0; i < edges.length; i++) {
36+
int x = find(nums, edges[i][0]);
37+
int y = find(nums, edges[i][1]);
3238

33-
for (int i = 0; i < edges.length; i++) {
34-
int x = find(nums, edges[i][0]);
35-
int y = find(nums, edges[i][1]);
39+
if (x == y) {
40+
return false;
41+
}
3642

37-
if (x == y) {
38-
return false;
43+
//union
44+
nums[x] = y;
3945
}
4046

41-
//union
42-
nums[x] = y;
47+
return edges.length == n - 1;
4348
}
4449

45-
return edges.length == n - 1;
46-
}
47-
48-
int find(int[] nums, int i) {
49-
if (nums[i] == i) {
50-
return i;
50+
int find(int[] nums, int i) {
51+
if (nums[i] == i) {
52+
return i;
53+
}
54+
return find(nums, nums[i]);
5155
}
52-
return find(nums, nums[i]);
5356
}
5457
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy