Re: [閒聊] 每日leetcode已回收

看板Marginalman作者 (南爹摳打)時間1年前 (2024/06/06 09:50), 1年前編輯推噓3(300)
留言3則, 3人參與, 1年前最新討論串320/1548 (看更多)
846. Hand of Straights 給定一整數陣列和分組大小 回傳可否把數字分組,每一組的數字要連續 Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 Output: true Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8] Example 2: Input: hand = [1,2,3,4,5], groupSize = 4 Output: false Explanation: Alice's hand can not be rearranged into groups of 4. 思路: 先把數字出現次數記起來 找出一組裡最小的數字 把後面幾組都扣掉同樣次數,扣失敗就return false C# code: public class Solution { public bool IsNStraightHand(int[] hand, int groupSize) { if (hand.Length % groupSize != 0) return false; var dict = new Dictionary<int, int>(); foreach (int key in hand) { if (dict.ContainsKey(key)) dict[key]++; else dict[key] = 1; } var keys = dict.Keys.ToList(); keys.Sort(); foreach (int start in keys) { if (dict.TryGetValue(start, out int count) == false) continue; for (int i = 0; i < groupSize; i++) { int key = start + i; if (dict.ContainsKey(key) == false) return false; dict[key] -= count; if (dict[key] < 0) return false; if (dict[key] == 0) { dict.Remove(key); } } } return true; } } -- (づ′・ω・)づ -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.248.96.37 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1717638646.A.0DA.html ※ 編輯: SecondRun (60.248.96.37 臺灣), 06/06/2024 09:52:11

06/06 09:55, 1年前 , 1F
大師
06/06 09:55, 1F

06/06 10:15, 1年前 , 2F
別捲了
06/06 10:15, 2F

06/06 11:12, 1年前 , 3F
大師
06/06 11:12, 3F
文章代碼(AID): #1cOHNs3Q (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cOHNs3Q (Marginalman)