150強訪談簡單

順手牌

「直手牌」問題的詳細指南和 Python 實作。

問題陳述

簡單

Alice 有一定數量的卡片,她想將卡片重新排列成群組,以便每個群組的大小為 groupSize,並由 groupSize 連續的卡片組成。給定一個整數數組 hand,其中 hand[i] 是第 i 張卡片上寫的值和一個整數 groupSize,如果她可以重新排列卡片,則返回 True,否則返回 False。

寫一個函數 isNStraightHand(hand: List[int], groupSize: int) -> bool

約束條件
  • 1 <= len(hand) <= 10^4
  • 0 <= hand[i] <= 10^9
  • 1 <= groupSize <= len(hand)

範例

Example 1
Input
hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output
True
Explanation

[1,2,3], [2,3,4], [6,7,8] are consecutive groups of 3.

Example 2
Input
hand = [1,2,3,4,5], groupSize = 4
Output
False
Explanation

Cannot rearrange cards into consecutive groups of 4.

Need a Hint?
考慮使用特定於貪婪的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。