LeetCode: Find Center Of Star Graph Solution

Approach

Way 1: use hashmap to find the node which has edge to all others

Way 2: because there's only one center, check the first two

Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {number[][]} edges3 * @return {number}4 */5var findCenter = function (edges) {6  let map = new Map()7  for (const [x, y] of edges) {8    if (!map.has(x)) {9      map.set(x, new Set())10    }11    if (!map.has(y)) {12      map.set(y, new Set())13    }14    map.set(x, map.get(x).add(y))15    map.set(y, map.get(y).add(x))16  }17
18  let res19  let max = -Infinity20  for (const [node, set] of map) {21    if (set.size > max) {22      res = node23      max = set.size24    }25  }26
27  return res28}29
30var findCenter = function (edges) {31  return edges[0].filter(node => edges[1].includes(node))[0]32}```

leetcode

graph

Next Post

LeetCode: Check If One String Swap Can Make Strings Equal

Mar 14, 2021

Search Posts