LeetCode 题解工作台
统计最大组的数目
给定一个整数 n 。 我们需要根据数字的数位和将 1 到 n 的数字分组。例如,数字 14 和 5 属于 同一 组,而数字 13 和 3 属于 不同 组。 返回最大组的数字数量,即元素数量 最多 的组。 示例 1: 输入: n = 13 输出: 4 解释: 总共有 9 个组,将 1 到 13 按数位…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 哈希·数学
答案摘要
我们注意到数字范围不超过 ,因此数位和的范围也不超过 $9 \times 4 = 36$,因此我们可以用哈希表或者一个长度为 的数组 来统计每个数位和的个数,用一个变量 表示最大的数位和个数。 我们在 中枚举每个数,计算其数位和 ,然后将 加 ,如果 $mx \lt cnt[s]$,则更新 $mx = cnt[s]$,并将 置为 ,如果 $mx = cnt[s]$,则将 加 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路
题目描述
给定一个整数 n 。
我们需要根据数字的数位和将 1 到 n 的数字分组。例如,数字 14 和 5 属于 同一 组,而数字 13 和 3 属于 不同 组。
返回最大组的数字数量,即元素数量 最多 的组。
示例 1:
输入:n = 13 输出:4 解释:总共有 9 个组,将 1 到 13 按数位求和后这些组分别是: [1,10],[2,11],[3,12],[4,13],[5],[6],[7],[8],[9]。总共有 4 个组拥有的数字并列最多。
示例 2:
输入:n = 2 输出:2 解释:总共有 2 个大小为 1 的组 [1],[2]。
提示:
1 <= n <= 104
解题思路
方法一:哈希表或数组
我们注意到数字范围不超过 ,因此数位和的范围也不超过 ,因此我们可以用哈希表或者一个长度为 的数组 来统计每个数位和的个数,用一个变量 表示最大的数位和个数。
我们在 中枚举每个数,计算其数位和 ,然后将 加 ,如果 ,则更新 ,并将 置为 ,如果 ,则将 加 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 为给定的数字。
class Solution:
def countLargestGroup(self, n: int) -> int:
cnt = Counter()
ans = mx = 0
for i in range(1, n + 1):
s = 0
while i:
s += i % 10
i //= 10
cnt[s] += 1
if mx < cnt[s]:
mx = cnt[s]
ans = 1
elif mx == cnt[s]:
ans += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n \log n) because computing digit sums takes log n operations per number. Space complexity is O(\log n) for storing the hash table of digit sum counts, which grows with the number of possible digit sums. |
| 空间 | O(\log n) |
面试官常问的追问
外企场景- question_mark
Checks if you understand digit sum computation and its connection to group formation.
- question_mark
Wants to see correct use of hash table to count frequencies efficiently.
- question_mark
Looks for awareness of edge cases, like multiple groups sharing the maximum size.
常见陷阱
外企场景- error
Forgetting that multiple numbers can have the same digit sum leading to incorrect counts.
- error
Assuming group sizes are always unique, missing ties for largest size.
- error
Using arrays instead of a hash table, which increases complexity unnecessarily.
进阶变体
外企场景- arrow_right_alt
Find the largest group itself instead of counting how many share the size.
- arrow_right_alt
Compute groups based on product of digits rather than sum.
- arrow_right_alt
Allow numbers with leading zeros in digit sum calculation for extended variant.