LeetCode 题解工作台

统计最大组的数目

给定一个整数 n 。 我们需要根据数字的数位和将 1 到 n 的数字分组。例如,数字 14 和 5 属于 同一 组,而数字 13 和 3 属于 不同 组。 返回最大组的数字数量,即元素数量 最多 的组。 示例 1: 输入: n = 13 输出: 4 解释: 总共有 9 个组,将 1 到 13 按数位…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·数学

bolt

答案摘要

我们注意到数字范围不超过 ,因此数位和的范围也不超过 $9 \times 4 = 36$,因此我们可以用哈希表或者一个长度为 的数组 来统计每个数位和的个数,用一个变量 表示最大的数位和个数。 我们在 中枚举每个数,计算其数位和 ,然后将 加 ,如果 $mx \lt cnt[s]$,则更新 $mx = cnt[s]$,并将 置为 ,如果 $mx = cnt[s]$,则将 加 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·数学 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个整数 n 。

我们需要根据数字的数位和将 1n 的数字分组。例如,数字 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
lightbulb

解题思路

方法一:哈希表或数组

我们注意到数字范围不超过 10410^4,因此数位和的范围也不超过 9×4=369 \times 4 = 36,因此我们可以用哈希表或者一个长度为 4040 的数组 cntcnt 来统计每个数位和的个数,用一个变量 mxmx 表示最大的数位和个数。

我们在 [1,..n][1,..n] 中枚举每个数,计算其数位和 ss,然后将 cnt[s]cnt[s]11,如果 mx<cnt[s]mx \lt cnt[s],则更新 mx=cnt[s]mx = cnt[s],并将 ansans 置为 11,如果 mx=cnt[s]mx = cnt[s],则将 ansans11

最后返回 ansans 即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 (logn)(\log n)。其中 nn 为给定的数字。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

统计最大组的数目题解:哈希·数学 | LeetCode #1399 简单