One minute
Leetcode 1791
1791. Find Center of Star Graph
This solution is straightforward.
- We first make an array called
nodes
withedges + 1
values. We neededges + 1
values becauselen(edges)
is the number of edge nodes, and the+ 1
is for the center node. We only neededges + 1
nodes because the nodes are from1...n
. - Then we loop through
edges
and get eachedge
.edge[0]
andedge[1]
are the two values given per edge. One of them is the center node, and the other one is the edge. We add one tonode[edge[0]]
andnode[edge[1]]
. - Inside the loop we check whether
nodes[edge[0]]
andnodes[edge[1]]
equals2
because the only node that repeats twice is the center node. And ifnodes[edge[0]] == 2
ornodes[edge[1]] == 2
we should return the center node.
(Note: The problem says 3 <= n <= 10^5
, but if it didn’t at the end the code returns edge[0][0]
becuase of the test case len(edges) == 1
)
func findCenter(edges [][]int) int {
nodes := make([]int, len(edges) + 2)
for _, edge := range edges {
nodes[edge[0]]++
nodes[edge[1]]++
if nodes[edge[0]] == 2 {
return edge[0]
}
if nodes[edge[1]] == 2 {
return edge[1]
}
}
return edges[0][0]
}
Read other posts