自己写的AC代码:
class Solution {
public:
int countBalls(int lowLimit, int highLimit) {
vector<int> cnt(highLimit+1,0);
int res = 0;
for(int i = lowLimit;i <= highLimit;i++)
{
cnt[calsum(i)]++;
}
for(int i = 0;i < cnt.size();i++)
{
res = max(res,cnt[i]);
}
return res;
}
private:
int calsum(int num){
int res = 0;
while(num){
res += num %10;
num /= 10;
}
return res;
}
};
运行效率:
Runtime: 24 ms, faster than 59.07% of C++ online submissions for Maximum Number of Balls in a Box.
Memory Usage: 13.3 MB, less than 5.21% of C++ online submissions for Maximum Number of Balls in a Box.
存在几点优化的点:
1.输入数据1 <= lowLimit <= highLimit <= 10的5次方,因此求和最大99999 ----> 5*9 =45;
2.求数组 vector等最大值stl存在方法,性能更高
优化后的代码:
class Solution {
public:
int countBalls(int lowLimit, int highLimit) {
int cnt[46] = {0};
for(int i = lowLimit;i <= highLimit;i++)
{
int n = i,sum = 0;
while(n)
{
sum += n%10;
n /= 10;
}
cnt[sum]++;
}
return *max_element(begin(cnt),end(cnt));
}
};
运行效率:
Runtime: 8 ms, faster than 93.52% of C++ online submissions for Maximum Number of Balls in a Box.
Memory Usage: 5.9 MB, less than 94.01% of C++ online submissions for Maximum Number of Balls in a Box.