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

LeetCode 3712: Sum of Elements With Frequency Divisible by K

·1 分鐘· ·
LeetCode Easy Hash-Table Counting Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2025-10-12

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

解題思路
#

先用 Counter 數每個值出現幾次(Hash Table 模板一)。次數能被 k 整除的值,每一次出現都要加,所以加上 值 × 次數。

我的解法
#

class Solution:
    def sumDivisibleByK(self, nums: List[int], k: int) -> int:
        return sum(x * c for x, c in Counter(nums).items() if c % k == 0)

複雜度
#

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

要特別避免的錯誤
#

  • 要加的是每一次出現,不是只加一次值。

面試口說整理
#

我數每個值的次數,次數能被 k 整除的就把值乘上次數加進答案。時間 O(n)。

相關文章

LeetCode 1160: Find Words That Can Be Formed by Characters
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 1160 解題筆記:每個單字的字元次數都不超過 chars 的次數才算能組成,加總這些單字的長度
LeetCode 1128: Number of Equivalent Domino Pairs
·1 分鐘
LeetCode Easy Array Hash-Table Counting
LeetCode 1128 解題筆記:把每張骨牌正規化成 (小, 大) 當 key 計數,每個 key 有 c 張就有 c(c - 1) / 2 對
LeetCode 914: X of a Kind in a Deck of Cards
·1 分鐘
LeetCode Easy Array Hash-Table Math Counting
LeetCode 914 解題筆記:每種卡片的張數都要能被同一個 X >= 2 整除,也就是所有張數的 GCD >= 2
LeetCode 819: Most Common Word
·1 分鐘
LeetCode Easy Array Hash-Table String Counting
LeetCode 819 解題筆記:標點換成空白、全部轉小寫再切單字,計數後找出不在 banned 裡的最多的那個
LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪
LeetCode 3541: Find Most Frequent Vowel and Consonant
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 3541 解題筆記:數每個字元的次數,母音取最大、子音取最大再相加;沒有的那一類算 0