概述
题目:
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
Explanation: As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
Example 2:
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
Constraints:
3 <= n <= 105
edges.length == n - 1
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
- The given
edges
represent a valid star graph.
思路1:
本题寻找的是中心点,其实就是出现最多的点,或者说找频数最大的点。那么直接用一个哈希map来记录每个点出现的次数,知道出现频数最大的点即可。
代码1:
class Solution {
public:
int findCenter(vector<vector<int>>& edges) {
int count=-1;
int ans=-1;
unordered_map<int,int> record;
for(auto &e:edges)
{
record[e[0]]++;
if(record[e[0]]>count)
{
count=record[e[0]];
ans=e[0];
}
record[e[1]]++;
if(record[e[1]]>count)
{
count=record[e[1]];
ans=e[1];
}
}
return ans;
}
};
思路2:
如果仔细读题,有一句话很关键,就是总共是n个点和n-1条边,并且center node和其他每一个都有连接,那么说明了就是一个中心点发散出去,其他非中心点之间根本没有连接,否则边数是不够的。这里评论区的神人用了一行来解决:取edges的前两个,我们称为[a, b]和[c,d],那么因为中心点和其他边必相连,那这两对中必出现两次中心点,而出现两次的那个数就是我们要找的。如果a和c相等或者a和d相等,我们直接返回a,否则就返回b。这个思路精准得切中题目,并且不需要额外的存储空间。
代码2:
class Solution {
public:
int findCenter(vector<vector<int>>& edges) {
return edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1] ? edges[0][0] : edges[0][1];
}
};
最后
以上就是单薄萝莉为你收集整理的1791. Find Center of Star Graph的全部内容,希望文章能够帮你解决1791. Find Center of Star Graph所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复