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

【Leetcode】python – [846] Hand of Straights 個人解法筆記

題目出處

846. Hand of Straights

難度

medium

個人範例程式碼

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if not len(hand) % groupSize == 0:
            return False

        counter = Counter(hand)
        # print(counter.items())
        for key in sorted(counter.keys()):
            if counter[key] == 0:
                continue
            if counter[key] > 0:
                num_of_cards = counter[key]
                for delta_i in range(groupSize):
                    # print(key + delta_i)
                    counter[key + delta_i] -= num_of_cards
                    if counter[key + delta_i] < 0:
                        return False

        return True

最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解

算法說明

先處理不整除的狀況,直接 return False

如果是整除的情況,我們先進行排序,
從小的卡片開始,往後「扣除最小卡片的數量」,

搜尋卡片的過程中,我們順便判斷剩餘的卡片數量是否大於 0,
等於 0 表示沒有剩餘,我們採取 continue 的動作。

input handling

先處理不整除的狀況,直接 return False

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
⭐ Binary Serach 相關題型 ⭐
33Search in Rotated Sorted ArrayBinary SerachArrayPython #重要題型
34Find First and Last Position of Element in Sorted ArrayBinary SerachPython
50Pow(x, n) Binary Serach