↓快轉到主要內容
  1. LeetCode/

LeetCode 3895: Count Digit Appearances

·1 分鐘· ·
LeetCode Medium Math Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-08-24

  • 提交紀錄:Accepted(一次通過)

解題思路
#

雖然標成 Medium,做法就是每個數字轉成字串、用 count 數出現次數、加總。也可以用 % 10 一位一位比對。

我的解法
#

class Solution:
    def countDigitOccurrences(self, nums: List[int], digit: int) -> int:
        target = str(digit)
        return sum(str(x).count(target) for x in nums)

複雜度
#

時間 O(n · d),空間 O(d)。

要特別避免的錯誤
#

  • digit 是整數,要轉成字串才能用 str.count。

面試口說整理
#

我把每個數字轉成字串,數 digit 出現幾次再加總。如果不想轉字串,就用 % 10 拿每一位比對。時間 O(n · d)。

相關文章

LeetCode 3828: Final Element After Subarray Deletions
·1 分鐘
LeetCode Medium Math Brainteaser Game-Theory Array
LeetCode 3828 解題筆記:Alice 第一步就能只留下頭或尾,所以至少拿到 max(頭, 尾);Bob 每次也能只留下目前的頭或尾,而 Alice 的一次刪除最多改變其中一端,所以答案就是 max(頭, 尾)
LeetCode 1040: Moving Stones Until Consecutive II
·1 分鐘
LeetCode Medium Sliding-Window Math Sorting Array
LeetCode 1040 解題筆記:最多步數 = 總空位 − 第一步會浪費掉的那一邊空隙;最少步數用長度 n 的視窗找最多石頭,n - 1 顆已連續、剩一顆在遠處時要特判成 2
LeetCode 3649: Number of Perfect Pairs
·1 分鐘
LeetCode Medium Two-Pointers Math Sorting Array
LeetCode 3649 解題筆記:把條件化簡成「較大的絕對值 <= 2 × 較小的絕對值」,排序絕對值後用雙指針計數
LeetCode 3618: Split Array by Prime Indices
·1 分鐘
LeetCode Medium Math Number-Theory Sieve Array
LeetCode 3618 解題筆記:判斷的是 index 是不是質數;用埃氏篩一次算出 0..n-1 哪些是質數,比每個 index 試除快
LeetCode 3627: Maximum Median Sum of Subsequences of Size 3
·1 分鐘
LeetCode Medium Math Greedy Sorting Game-Theory Array
LeetCode 3627 解題筆記:排序後每次拿最大的兩個和最小的一個,中位數是第二大的;答案是從尾端往前每隔一個取,共 n / 3 個
LeetCode 1814: Count Nice Pairs in an Array
·1 分鐘
LeetCode Medium Array Hash-Table Math Counting
LeetCode 1814 解題筆記:把條件移項成 nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]),按這個值分組數 pair,記得取模