0
点赞
收藏
分享

微信扫一扫

LeetCode Algorithm 1791. 找出星型图的中心节点

题目链接:​​1791. 找出星型图的中心节点​​

Ideas

算法:计数
数据结构:图
思路:中心节点其实就是度为n-1的节点,所以我们可以用一个计数器统计所有节点的度,如果度为n-1,那么它就是中心节点。题目的输入中并没有给定n,所以这个是自己去找的,而且题目给出的是一个二维数组,不好操作,最好可以将其拉平为一维数组,参考文章:​将不规则的Python多维数组拉平到一维。

Code

Python

class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
from itertools import chain
from collections import Counter

array = list(chain(*edges))
n = max(array)
cnt = Counter(array)
for key, val in cnt.items():
if val == n - 1:
return key


举报

相关推荐

0 条评论