Re: [閒聊] 每日leetcode

看板Marginalman作者 (leaf)時間6月前 (2025/05/12 22:49), 編輯推噓1(100)
留言1則, 1人參與, 6月前最新討論串1426/1548 (看更多)
2094. Finding 3-Digit Even Numbers https://leetcode.com/problems/finding-3-digit-even-numbers/description 給定一個數組, 返回用數組中的數字組成偶數的三位數整數的所有組合, 數字組合不含前導零, 且數組應按升序排列 -- 思路: 因為數組的排列不影響答案, 所以先用一個字典統計各數字的數量, 接著遍歷所有組合 先是找個位數, 因最後的結果必須是偶數所以跑02468即可, 原數組沒有的話就跳過 再來找百位數, 因結果不能有前導零只要找1到9就行, 並且如果遍歷到的數字數量為0, 或遍歷到的數字與個位相同但數量小於1也要跳過 此處寫成條件count[j] == 0 or (j == i and count[j] <= 1), 可以簡化為count[j] - (j == i) <= 0的寫法 最後遍歷十位數, 採用跟剛剛相同的檢查手法即可, 再將數組做排序 -- Python code: class Solution: def findEvenNumbers(self, digits: List[int]) -> List[int]: ans = [] count = {_:0 for _ in range(10)} for d in digits: count[d] += 1 for i in (0,2,4,6,8): if count[i] == 0: continue for j in range(1, 10): if count[j] - (j == i) <= 0: continue for k in range(10): if count[k] - (k == j) - (k == i) > 0: ans.append(j * 100 + k * 10 + i) ans.sort() return ans -- https://i.imgur.com/AhNjoAu.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.163.151.236 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1747061360.A.64E.html

05/12 23:12, 6月前 , 1F
幹我寫的好醜 我吐了
05/12 23:12, 1F
文章代碼(AID): #1e8WfmPE (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1e8WfmPE (Marginalman)