0
点赞
收藏
分享

微信扫一扫

Leetcode 1399. 统计最大组的数目

Leetcode 1399. 统计最大组的数目_算法
给你一个整数 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

主要思路:转换成string和map
Code:

class Solution {
public:
typedef pair<int, int> PAIR;

struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.second > rhs.second;
}
};
int addStr(string str)
{
int res=0;
for(int i=0;i<str.length();i++)
{
res+=(str[i]-'0');
}
return res;
}

int countLargestGroup(int n) {

int res=1;
std::pair<std::map<int,int>::iterator,bool> ret;

map<int,int>mymap;
for(int i=1;i<=n;i++)
{
mymap[addStr(to_string(i))]++;
}



//把map中元素转存到vector中
vector<PAIR> name_score_vec(mymap.begin(), mymap.end());

//对vector排序
sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());


if(name_score_vec.size()>1)
{
res=1;
for(int i=1;i<name_score_vec.size();i++)
{
// cout<<name_score_vec[i].second<<endl;
if(name_score_vec[i].second<name_score_vec[i-1].second)
{
break;
}
else
res++;
}
}
// map<int,int>::iterator it;
// for(it=mymap.begin();it!=mymap.end();++it)
// {
// cout<<it->first<<" "<<it->second<<endl;
// }
cout<<"res="<<res<<endl;
return res;
}
};


举报

相关推荐

0 条评论