1399. Count Largest Group

Given an integer n. Each number from 1 to n is grouped according to the sum of its digits. 

Return how many groups 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.

Example 3:

Input: n = 15
Output: 6

Example 4:

Input: n = 24
Output: 5
class Solution {
    public int countLargestGroup(int n) {
        Map<Integer, Integer> map = new HashMap();
        int freq = 0;
        for(int i = 1; i <= n; i++){
            int tmp = help(i);
            map.put(tmp, map.getOrDefault(tmp, 0) + 1);
        }
        for(Map.Entry<Integer, Integer> entry: map.entrySet()){
            int tmp = entry.getValue();
            freq = Math.max(freq, tmp);
        }
        int res = 0;
        for(Map.Entry<Integer, Integer> entry: map.entrySet()){
            int tmp = entry.getValue();
            if(tmp == freq) res++;
        }
        return res;
    }
    public int help(int n){
        int res = 0;
        while(n != 0){
            int i = n % 10;
            res += i;
            n /= 10;
        }
        return res;
    }
}

题目意思是从1到n,把数字按位数加起来,相同的sum为一组,求组的size最大的有多少组。禁止套娃

好像烦了点?先记录出现的sum和出现的频率,再算出最大频率时sum出现的次数即可。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/12718212.html