項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 widget-area-1 尚未註冊或是沒有一個 view.php 檔案.
項目 search-input 尚未註冊或是沒有一個 view.php 檔案.

【Leetcode】python – [496] Next Greater Element I 個人解法筆記

題目出處

496. Next Greater Element I

難度

easy

個人範例程式碼

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:

        ans_hashtable = {}
        stack = []

        for num in nums2:
            while stack and stack[-1] < num: # new is greater
                ans_hashtable[stack[-1]] = num # last number's answer = this num
                del stack[-1]            
            stack.append(num)

        for rest_element in stack:
            ans_hashtable[rest_element] = -1

        return [ans_hashtable[num] for num in nums1]

算法說明

像這類有「找後續/前綴」中比較大或比較小的第一個數字,
我們通常會用 stack 來保存「等待被決定的內容」。

當我們發現「stack[-1]」<「新的數字」,表示找到答案,
我們 pop[-1] 出 stack,並記錄「 pop 的答案就是當前數字 」。

最後剩下在 stack 的內容,答案都是 -1

input handling

如果沒有 nums, 回傳 [] (題目沒特別要求)

Boundary conditions

用 for 迴圈控制範圍

Reference

⭐ Leetcode 解題紀錄 ⭐題型資料結構Python SolutionC++ SolutionNote
⭐BFS 相關題型 ⭐
104Maximum Depth of Binary TreeBFS (分層)Python
94Binary Tree Inorder TraversalBFS (分層)TreePython 內含 處理 Tree 樹問題的重點
102Binary Tree Level Order TraversalBFS (分層)TreePython
103Binary Tree Zigzag Level Order TraversalBFS (分層)TreePython
107Binary Tree Level Order Traversal IIBFS (分層)TreePython
133Clone GraphBFS (分層)GraphPython Graph 的基本操作 #重要題型
127Word LadderBFS (分層), DFSGraphPython
[Lint] 127Topological SortingBFS (拓撲)Python
內有 indegree, outdegree 介紹 #重要題型
207Course ScheduleBFS (拓樸)GraphPython
210Course Schedule IIBFS (拓樸)GraphPython
[Lint] 892Alien DictionaryBFS (拓樸)GraphPython
[Lint] 431Connected Component in Undirected GraphBFS (連通塊)GraphPython 內含 BFS 模板 #重要題型
1091Shortest Path in Binary MatrixBFS (最短路徑)MatrixPython