Algorithm/LeetCode
[LeetCode] 1791. Find Center of Star Graph
Eric_Park
2021. 8. 13. 10:03
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.
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
import itertools
new_edges = list(itertools.chain.from_iterable(edges))
s1 = list(set(new_edges)) # set 으로 unique value
s2 = [0 for i in range(len(s1))] # count +=1 하기 위해서 리스트 생성
dict1 = dict(zip(s1,s2)) # dict 형태로 리스트 요소들 변환
for k in new_edges:
if k in dict1:
dict1[k] +=1
key_max = max(dict1.keys(), key=(lambda k:dict1[k])) # key, value 에서 value counting
return key_max
#Runtime: 764 ms, faster than 96.66% of Python3 online submissions for Find Center of Star Graph.
#Memory Usage: 50.4 MB, less than 21.36% of Python3 online submissions for Find Center of Star Graph.
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
f=edges[0][0]
s=edges[0][1]
if(f in edges[1]):
return f
else:
return s
# 문제의 특징을 잘 잡고 간결하게 풀어냈음.. bb