报错:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_replace_aux
猜测原因:超过string的最大长度,而string超出范围猜测是因为前面对于数字个数的统计是出了问题的。。。可能超出int数组的最大范围了
解决:把num[10]的类型改成long long就OK了
class Solution {
public:
string largestMultipleOfThree(vector<int>& digits) {
int l = digits.size();
// 本来是int num,但是对于字符串进行数字统计的时候会超出范围
long long num[10];
string res = "";
int sum = 0;
for(int i = 0; i < l; i++) {
int tmp = digits[i];
num[tmp] ++;
sum += tmp;
}
// 难点在于如果不是3的倍数,我们需要减去多少个数字才能让其可以被3整除?限制其只减去一个数字可以吗???
// 应该是可以的,sum%3==1,那我们减去数字钟%3==1最小的数字;sum%3==2的情况是一样的
int mod = sum % 3;
if(mod != 0){
for(int i = 0; i < 10; i ++) {
if(i % 3 == mod && num[i] > 0) {
num[i] --;
sum -= i;
break;
}
}
int cnt = 0;
int begin = 0;
while(begin <= 9 && sum % 3 != 0) {
if(num[begin] == 0 * 1L || begin % 3 != (3 - mod)) {
begin ++;
}
else {
if(begin % 3 == (3 - mod)){
num[begin] --;
sum -= begin;
cnt ++;
if(cnt == 2) {
break;
}
}
}
}
}
// 这个对于特别长的字符串会超出时间范围!
// if(sum % 3 == 0) {
// int last = 9;
// while (last >= 0) {
// // cout << last << " " << num[last] << endl;
// if(num[last] == 0) {
// last --;
// }
// else {
// res += (last + '0');
// num[last] -- ;
// }
// }
// }
for(int i = 9; i >= 0 && sum % 3 == 0; i --) {
res.append(num[i], char(i + '0'));
}
if(res[0] == '0' && res.size() > 0) res = "0";
return res;
}
};
学到的知识:对于string的append方法的了解更深了,要多读官方手册!
https://cplusplus.com/reference/string/string/append/
字符串 (1)
string& append (const string& str);
子字符串 (2)
string& append (const string& str, size_t subpos, size_t sublen);
C-String (3)
string& append (const char* s);
缓冲器 (4)
string& append (const char* s, size_t n);
填充 (5)
string& append (size_t n, char c);
范围 (6)
template <class InputIterator> string& append (InputIterator first, InputIterator last);
使用例子:
// appending to string
#include <iostream>
#include <string>
int main ()
{
std::string str;
std::string str2="Writing ";
std::string str3="print 10 and then 5 more";
// used in the same order as described above:
str.append(str2); // "Writing "
str.append(str3,6,3); // "10 "
str.append("dots are cool",5); // "dots "
str.append("here: "); // "here: "
str.append(10u,'.'); // ".........."
str.append(str3.begin()+8,str3.end()); // " and then 5 more"
str.append<int>(5,0x2E); // "....."
std::cout << str << '\n';
return 0;
}