当前位置:网站首页>LeetCode 1791. Find the central node of the star chart

LeetCode 1791. Find the central node of the star chart

2022-06-24 04:52:00 freesan44

subject

There is an undirected Star type chart , from n A number from 1 To n Node composition of . The star graph has a center node , And there is n - 1 The edges connect the central node to each other .

Here's a two-dimensional array of integers edges , among  edgesi = ui, vi At the node ui and vi There is an edge between . Please find out and return to  edges The center node of the star graph represented by .

image.png
 Example  1:


 Input :edges = [[1,2],[2,3],[4,2]]
 Output :2
 explain : As shown in the figure above , node  2  Connected to every other node , So node  2  It's the central node .
 Example  2:

 Input :edges = [[1,2],[5,1],[1,3],[1,4]]
 Output :1
``` 

Tips :

3 <= n <= 105

edges.length == n - 1

edgesi.length == 2

1 <= ui, vi <= n

ui != vi

The title data gives edges Represents an effective star graph

Their thinking

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        resList = []
        # Disassemble all the arrays to form one List, And then use Counter inductive , Find the quantity as n Of 
        for i in edges:
            resList += i
        # print(resList)
        from collections import Counter
        count = Counter(resList)
        for (key, val) in count.items():
            # print(key,val)
            # print(len(edges)-1)
            if val == (len(edges)):
                return key
        return 0

if __name__ == '__main__':
    edges = [[1,2],[2,3],[4,2]]
    ret = Solution().findCenter(edges)
    print(ret)
原网站

版权声明
本文为[freesan44]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210903184937249u.html