Skip to content

Latest commit

 

History

History
165 lines (130 loc) · 3.38 KB

File metadata and controls

165 lines (130 loc) · 3.38 KB

English Version

题目描述

给你一个整数 n 。请你先求出从 1 到 n 的每个整数 10 进制表示下的数位和(每一位上的数字相加),然后把数位和相等的数字放到同一个组中。

请你统计每个组中的数字数目,并返回数字数目并列最多的组有多少个。

 

示例 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]。

示例 3:

输入:n = 15
输出:6

示例 4:

输入:n = 24
输出:5

 

提示:

  • 1 <= n <= 10^4

解法

方法一:哈希表模拟

Python3

class Solution:
    def countLargestGroup(self, n: int) -> int:
        cnt = Counter()
        ans, mx = 0, 0
        for i in range(1, n + 1):
            t = sum(int(v) for v in str(i))
            cnt[t] += 1
            if mx < cnt[t]:
                mx = cnt[t]
                ans = 1
            elif mx == cnt[t]:
                ans += 1
        return ans

Java

class Solution {
    public int countLargestGroup(int n) {
        int[] cnt = new int[40];
        int mx = 0, ans = 0;
        for (int i = 1; i <= n; ++i) {
            int t = 0;
            int j = i;
            while (j != 0) {
                t += j % 10;
                j /= 10;
            }
            ++cnt[t];
            if (mx < cnt[t]) {
                mx = cnt[t];
                ans = 1;
            } else if (mx == cnt[t]) {
                ++ans;
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    int countLargestGroup(int n) {
        vector<int> cnt(40);
        int mx = 0, ans = 0;
        for (int i = 1; i <= n; ++i) {
            int t = 0;
            int j = i;
            while (j) {
                t += j % 10;
                j /= 10;
            }
            ++cnt[t];
            if (mx < cnt[t]) {
                mx = cnt[t];
                ans = 1;
            } else if (mx == cnt[t])
                ++ans;
        }
        return ans;
    }
};

Go

func countLargestGroup(n int) int {
	cnt := make([]int, 40)
	mx, ans := 0, 0
	for i := 1; i <= n; i++ {
		t := 0
		j := i
		for j != 0 {
			t += j % 10
			j /= 10
		}
		cnt[t]++
		if mx < cnt[t] {
			mx = cnt[t]
			ans = 1
		} else if mx == cnt[t] {
			ans++
		}
	}
	return ans
}

...