# Leetcode [No. 1791] Find Center of Star Graph (EASY) 解題心得 + Solved on 2024/06/27 Daily Challenge ## 題目 https://leetcode.com/problems/find-center-of-star-graph/description/?envType=daily-question&envId=2024-06-27 這題目的目的是要你找到哪一個node有連到其他所有的node ## 思路 + 這個解法就是用一個hashMap去紀錄哪一個node有連到所有的node. ```c++= class Solution { public: int findCenter(vector<vector<int>>& edges) { unordered_map<int,int> cntMap; for (auto edge : edges) { for (auto v : edge) { cntMap[v]++; } } for(auto& iter : cntMap) { if(iter.second == edges.size()) { return iter.first; } } return -1; } }; ``` ### 解法分析 + time complexity: $O(2*n)$ ### 執行結果  ## follow up: + 看了一下solution的方法,會發現除了center node以外其他人都只會出現一次,所以可以改一下判斷的條件 ```C++= class Solution { public: int findCenter(vector<vector<int>>& edges) { unordered_map<int,int> cntMap; for (auto edge : edges) { for (auto v : edge) { if(cntMap[v] > 0) return v; cntMap[v]++; } } return -1; } }; ``` ### 解法分析 + time complexity: O(2n) ### 執行結果 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up