
题目描述
给你一个整数数组 nums 和一个整数 k。
请返回一个整数,表示 nums 中所有其 出现次数 能被 k 整除的元素的总和;如果没有这样的元素,则返回 0 。
注意: 若某个元素在数组中的总出现次数能被 k 整除,则它在求和中会被计算 恰好 与其出现次数相同的次数。
元素 x 的 出现次数 指它在数组中出现的次数。
示例 1:
输入: nums = [1,2,2,3,3,3,3,4], k = 2
输出: 16
解释:
- 数字 1 出现 1 次(奇数次)。
- 数字 2 出现 2 次(偶数次)。
- 数字 3 出现 4 次(偶数次)。
- 数字 4 出现 1 次(奇数次)。
因此总和为 2 + 2 + 3 + 3 + 3 + 3 = 16。
示例 2:
输入: nums = [1,2,3,4,5], k = 2
输出: 0
解释:
没有元素出现偶数次,因此总和为 0。
示例 3:
输入: nums = [4,4,4,1,2,3], k = 3
输出: 12
解释:
- 数字 1 出现 1 次。
- 数字 2 出现 1 次。
- 数字 3 出现 1 次。
- 数字 4 出现 3 次。
因此总和为 4 + 4 + 4 = 12。
提示:
1 <= nums.length <= 100
1 <= nums[i] <= 100
1 <= k <= 100
解法
方法一:计数
我们用一个哈希表 \(\textit{cnt}\) 来记录每个数字的出现次数。遍历数组 \(\textit{nums}\),对于每个数字 \(x\),我们将 \(\textit{cnt}[x]\) 增加 \(1\)。
然后,我们遍历哈希表 \(\textit{cnt}\),对于每个元素 \(x\),如果它的出现次数 \(\textit{cnt}[x]\) 能被 \(k\) 整除,就将 \(x\) 乘以它的出现次数加到结果中。
时间复杂度为 \(O(n)\),其中 \(n\) 是数组的长度。空间复杂度为 \(O(m)\),其中 \(m\) 是数组中不同元素的数量。
| class Solution:
def sumDivisibleByK(self, nums: List[int], k: int) -> int:
cnt = Counter(nums)
return sum(x * v for x, v in cnt.items() if v % k == 0)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | class Solution {
public int sumDivisibleByK(int[] nums, int k) {
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) {
cnt.merge(x, 1, Integer::sum);
}
int ans = 0;
for (var e : cnt.entrySet()) {
int x = e.getKey(), v = e.getValue();
if (v % k == 0) {
ans += x * v;
}
}
return ans;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | class Solution {
public:
int sumDivisibleByK(vector<int>& nums, int k) {
unordered_map<int, int> cnt;
for (int x : nums) {
++cnt[x];
}
int ans = 0;
for (auto& [x, v] : cnt) {
if (v % k == 0) {
ans += x * v;
}
}
return ans;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12 | func sumDivisibleByK(nums []int, k int) (ans int) {
cnt := map[int]int{}
for _, x := range nums {
cnt[x]++
}
for x, v := range cnt {
if v%k == 0 {
ans += x * v
}
}
return
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13 | function sumDivisibleByK(nums: number[], k: number): number {
const cnt = new Map();
for (const x of nums) {
cnt.set(x, (cnt.get(x) || 0) + 1);
}
let ans = 0;
for (const [x, v] of cnt.entries()) {
if (v % k === 0) {
ans += x * v;
}
}
return ans;
}
|