- 作者: 負雪明燭
- id: fuxuemingzhu
- 個人博客:http://fuxuemingzhu.cn/
題目地址:https://leetcode-cn.com/problems/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
Constraints:
1 <= n <= 10^4
題目大意
給你一個整數 n 。請你先求出從 1 到 n 的每個整數 10 進製表示下的數位和(每一位上的數字相加),然後把數位和相等的數字放到同一個組中。
請你統計每個組中的數字數目,並返回數字數目並列最多的組有多少個。
解題方法
直接求
第一感覺:直接按照題目說的求。
第二感覺:應該會有規律出現的,但是提交bug了一次之後反應過來,所有的數字不止在 1~10 之間,比如當 n = 9999 時,所有數字的和是 4 * 9 = 36. 因此規律不好找,還是直接求吧。
直接求的方式就是按照題目說的,把 1 ~ n 中所有的數字,各個位的和加在一起。用一個數組(或者字典)保存各個數位和
出現的次數,然後統計最多出現的次數共有多少個。
由於數位和
最大也就是 當 n = 9999 時,數字和
爲 36,所以我開了一個 100 的數組來保存數字和
。
C++代碼如下。
class Solution {
public:
int countLargestGroup(int n) {
vector<int> count(100, 0);
for (int i = 1; i <= n; ++i) {
count[sum_digit(i)] ++;
}
int max = *max_element(count.begin(), count.end());
int res = 0;
for (int i = 0; i < 100; ++i) {
if (count[i] == max) {
res ++;
}
}
return res;
}
int sum_digit(int i) {
int sum = 0;
while (i > 0) {
sum += i % 10;
i /= 10;
}
return sum;
}
};
歡迎關注負雪明燭的刷題博客,leetcode刷題800多,每道都講解了詳細寫法!
日期
2020 年 4 月 5 日 —— 好久不打周賽了