Re: [閒聊] 每日LeetCode

作者: DJYOSHITAKA (Evans)   2024-02-23 00:53:44
1245. Tree Diameter
premium題 找出一個tree的最長path
看起來不太直覺 其實只是實作一個找depth的function
同時記下前兩深的subtree的深度 同時更新最長path長度
最長path必會是某個root的兩個最深subtree的深度相加再+2
DFS的過程就可以順便更新
寫起來不難 但不熟的話一開始會卡:( 希望有記起來
class Solution {
public:
int helper(unordered_map<int, vector<int>>& g, int root, int parent, int*
ans)
{
// calculate depth
int max_depth_1 = -1, max_depth_2 = -1;
for(auto n : g[root])
{
if(n != parent)
{
max_depth_2 = max(max_depth_2, helper(g, n, root, ans));
if(max_depth_2 > max_depth_1) swap(max_depth_1, max_depth_2);
}
}
// update ans
*ans = max(*ans, max_depth_1+max_depth_2+2);
// return depth
return max_depth_1+1;
}
int treeDiameter(vector<vector<int>>& edges) {
unordered_map<int, vector<int>> g;
for(auto e : edges)
{
g[e[0]].push_back(e[1]);
g[e[1]].push_back(e[0]);
}
int ans = 0;
int depth = helper(g, 0, -1, &ans);
return ans;
}
};
作者: wu10200512 (廷廷)   2024-02-23 00:55:00
你的每日怎麼跟我不一樣
作者: DJYOSHITAKA (Evans)   2024-02-23 00:56:00
課金題 對ㄚ==每周課金題
作者: pandix (麵包屌)   2024-02-23 00:57:00
大師
作者: wu10200512 (廷廷)   2024-02-23 00:57:00
課金題是三小 題庫裡沒有的喔
作者: DJYOSHITAKA (Evans)   2024-02-23 00:59:00
要買premium 可以等特價
作者: NCKUEECS (小惠我婆)   2024-02-23 01:03:00
大師
作者: JIWP (JIWP)   2024-02-23 01:09:00
大師
作者: JerryChungYC (JerryChung)   2024-02-23 01:21:00
https://i.imgur.com/RqqzvWh.png看到這篇才想到之前寫的程式鎖住的題目也能抓到不過不能在leetcode上送出也沒甚麼用就是了
作者: DJYOSHITAKA (Evans)   2024-02-23 01:25:00
大師:OOO

Links booklink

Contact Us: admin [ a t ] ucptt.com