310. Minimum Height Trees 前往題目 之前寫的文章 思路其實是Hard題目 計算每個node有多少indegree,因為indegree為1的一定是最外圍的node從外圍到中間 計算每個Node的鄰居有誰 從最外圈的Node開始循環,一層一層剝掉,所以indegree要減1 然後如果所有的node都看過了,就把當前node加入到結果,因為他一定是中間的,也就是答案之一 接著看這個node的鄰居,indegree不是0的話 2024-04-09 Leetcode > Medium #Leetcode #心得 #Depth-First Search #Breadth-First Search #Graph #Topological Sort
438. Find All Anagrams in a String - Medium 前往題目 之前寫的文章 想法 用map 用Sliding window 思路 備用array來儲存sliding window的資訊,另一個array用來儲存p的counts 開始疊代s,每次循環都看看是否和p array相等,超過p的長度時就開始把p長度之前的字母去掉,以保證window的size和p的length一樣 遇到array相等就加第一個字母的index到結果中 Codeclas 2024-04-09 Leetcode > Medium #Leetcode #心得 #String #Hash Table #Sliding Window
79. Word Search - Medium 前往題目 之前寫的文章 想法 找到首字母 DFS可能的路徑 思路 使用Backtracking(DFS) 每個cell都要DFS,沒有更優的演算法了 走過的path就標記,然後往上下左右去確認是否字母匹配 匹配就前往其他格子,並且匹配下一個字母,直到全部都符合 Codeclass Solution { int ROWS; int COLS; public 2024-04-08 Leetcode > Medium #Leetcode #心得 #Array #String #Matrix #Backtracking
17. Letter Combinations of a Phone Number - Medium 前往題目 之前寫的文章 思路 Map數字與字母 backtracking,取到需要的數量就加到答案裡 Codeclass Solution { private ArrayList<String> res; private Map<Character, String> digitToChar = Map.of( '2', "abc", 2024-04-08 Leetcode > Medium #Leetcode #心得 #String #Hash Table #Backtracking
11. Container With Most Water — Medium 前往題目 之前寫的文章 想法 雙指針 每次移動短的那邊 Greedy 思路 左右指針從array的開始與結尾 每個area都判斷一次是否大於maxArea 短的那邊移動,這樣才有機會取到更大的 直到左指針和右指針相撞結束 Codeclass Solution { public int maxArea(int[] height) { int max 2024-04-07 Leetcode > Medium #Leetcode #心得 #Array #Two Pointers #Greedy
105. Construct Binary Tree from Preorder and Inorder Traversal — Medium 前往題目 之前寫過的文章 想法 觀察inorder和preorder的規律 思路 preorder的第一項一定是root,這是它的特性 inorder的每個父節點,左邊一定是left subtree,右邊一定是right subtree 把inorder的val->index資訊存下來 builder function每個循環都取得當前值,以及取得mid的index 根據mid來呼叫bu 2024-04-07 Leetcode > Medium #Leetcode #心得 #Binary Tree #Array #Hash Table #Tree #Divide and Conquer
2017. Grid Game - Medium 前往題目 思路 計算第一列與第二列每一格的prefix sum 疊代一列 每一格都算出當前如果待在top可以拿到多少points,下去bottom可以拿到多少points robot2取top和bottom比較大的那個 結果是每次循環都盡可能取更小的robot2分數 Code Java版本 class Solution { public long gridGame(int[ 2024-04-05 Leetcode > Medium #Leetcode #心得 #Array #Matrix #Prefix Sum
62. Unique Paths - Medium 前往題目 之前寫的文章 思路這次自己寫出來了,只是用的是top-down而非bottom-up 第一行和第一列一定都是1,因為只能向右和向下走 每一格都是上與左一格的和 最後終點即是答案 Codetop-down class Solution { public int uniquePaths(int m, int n) { in 2024-04-03 Leetcode > Medium #Leetcode #心得 #Math #Dynamic Programming #Combinatorics
217. Contains Duplicate - Easy 前往題目 之前寫的文章 思路 使用HashSet Codeclass Solution { public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num : nums) { 2024-04-03 Leetcode > Easy #Leetcode #心得 #Array #Hash Table #Sorting
2215. Find the Difference of Two Arrays - Easy 前往題目 想法 用兩個set,各自裝nums1和nums2的元素,然後利用.contains來查看另一個是否也有,沒有的話就加到答案裡 思路同想法 Codeclass Solution { public List<List<Integer>> findDifference(int[] nums1, int[] nums2) { 2024-04-02 Leetcode > Easy #Leetcode #心得 #Array #Hash Table