LeetCode #1399. Count Largest Group

题目

1399. Count Largest Group


解题方法

设置一个字典dic和一个最大长度maxlen,从1开始遍历到n,计算每个数字的数位和并加入到对应的字典中,最后更新maxlen。之后设置返回值rat,遍历字典中的键,当键的长度等于maxlen时rat加1,遍历结束返回rat。
时间复杂度:O(n)
空间复杂度:O(n)


代码

class Solution:
    def countLargestGroup(self, n: int) -> int:
        dic = {}
        maxlen = 0
        
        for i in range(1, n+1):
            Sum = 0
            curnum = i
            while curnum:
                Sum += curnum % 10
                curnum //= 10
            if Sum not in dic:
                dic[Sum] = [i]
            else:
                dic[Sum].append(i)
            maxlen = max(maxlen, len(dic[Sum]))
        
        rat = 0
        for key in dic.keys():
            if len(dic[key]) == maxlen:
                rat += 1
        
        return rat
posted @ 2020-12-01 15:37  老鼠司令  阅读(75)  评论(0编辑  收藏  举报