统计最大组的数目
难度:
标签:
题目描述
You are given an integer n
.
Each number from 1
to n
is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
Example 1:
Input: n = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13: [1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9]. There are 4 groups with largest size.
Example 2:
Input: n = 2 Output: 2 Explanation: There are 2 groups [1], [2] of size 1.
Constraints:
1 <= n <= 104
代码结果
运行时间: 46 ms, 内存: 15.9 MB
解释
方法:
此题解通过计算1到n每个数字的数位和,并将计算结果用作字典的键,将相同数位和的数字数量累加存储在字典中。计算数位和时,利用了数位变化的规律,特别是在数字每过10、100、1000的边界时进行调整。最后,将字典中的值(即每个组的大小)进行排序,通过比较找出并列最多的组数。
时间复杂度:
O(n)
空间复杂度:
O(k),其中k为不同数位和的数量,远小于n
代码细节讲解
🦆
在计算数位和时,为什么在数字是10的倍数时需要进行特殊处理?
▷🦆
在调整数位和的过程中,为何当i是100的倍数时减17,而是10的倍数但非100的倍数时减8?这些特定的数值是如何得出的?
▷🦆
给出的算法在处理边界条件时,比如数字刚好是1000或更大的幂时,为什么需要将数位和归零并重新计算?
▷