There is an undirected star graph consisting of n
nodes labeled from 1
to n
. A star graph is a graph where there is one center node and exactly n - 1
edges that connect the center node with every other node.
You are given a 2D integer array edges
where each edges[i] = [ui, vi]
indicates that there is an edge between the nodes ui
and vi
. Return the center of the given star graph.
Example 1:
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Example 2:
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
Approach
C++
#include <bits/stdc++.h>using namespace std;int findCenter(vector<vector<int>> &edges){set<int> st;int res;for (int i = 0; i < edges.size(); i++){if (st.find(edges[i][0]) != st.end()){res = edges[i][0];break;}else if (st.find(edges[i][0]) == st.end())st.insert(edges[i][0]);if (st.find(edges[i][1]) != st.end()){res = edges[i][1];break;}elsest.insert(edges[i][1]);}return res;}int main(){vector<vector<int>> edges = {{1, 2}, {2, 3}, {4, 2}};cout << findCenter(edges) << "\n";return 0;}
No comments:
Post a Comment