LeetCode-Python-1399. Count the number of the largest group (simulation method + hash table)

 

1399. Count the number of largest groups

Simple difficulty 4

Give you an integer  n . Please first find the  sum of the digits in the decimal representation of each integer from (  1 to  nadd the digits on each digit), and then put the digits and the equivalent digits in the same group.

Please count the number of numbers in each group, and return the number of groups with the largest number of numbers in parallel.

 

Example 1:

Input: n = 13
 Output: 4
 Explanation: There are 9 groups in total. After summing the numbers from 1 to 13, the groups are: 
[1,10], [2,11], [3,12], [4 , 13], [5], [6], [7], [8], [9]. In total, there are 4 groups with the most numbers in parallel.

Example 2:

Input: n = 2
 Output: 2
 Explanation: There are 2 groups of size 1 [1], [2].

Example 3:

Input: n = 15
 Output: 6

Example 4:

Input: n = 24
 Output: 5

 

prompt:

  • 1 <= n <= 10^4

Ideas:

The simulation method directly counts the sum of digits of each number in [1, n] and puts it in the dictionary l, key is the sum of digits, and val is the number of occurrences of the sum of digits.

Then determine how many of the largest number of parallel digits in l is.

Time complexity: O (NlogN)

Space complexity: O (logN)

class Solution(object):
    def countLargestGroup(self, n):
        """
        :type n: int
        :rtype: int
        """
        from collections import defaultdict
        l = defaultdict(int)   

        def helper(num):
            # 计算num数位之和,eg:输入34, 返回3 + 4 = 7
            s = 0
            while num:
                num, tmp = divmod(num, 10)
                s += tmp
            return s

        for num in range(1, n + 1):
            l[helper(num)] += 1
        
        mmax = max(l.values())
        return sum([1 for item in l.values() if item == mmax])

 

Published 734 original articles · 121 praises · 210,000 views

Guess you like

Origin blog.csdn.net/qq_32424059/article/details/105549523