class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> tmp;
string ans;
for (size_t i = 0; i < nums.size(); ++i)
tmp.push_back(to_string(nums[i]));
sort(tmp.begin(), tmp.end(),
bind(&Solution::compare,
this, placeholders::_1, placeholders::_2));
for (auto it = tmp.rbegin(); it != tmp.rend(); ++it)
ans += *it;
return ans;
}
private:
bool compare(const string &lhs, const string &rhs) {
if (lhs.size() > rhs.size())
return !compare(rhs, lhs);
int len1 = lhs.size();
int len2 = rhs.size();
if (lhs[0] != rhs[0]) {
return lhs[0] < rhs[0];
} else {
if (len1 != 1) {
return compare(lhs.substr(1), rhs.substr(1));
} else {
auto pos = rhs.find_first_not_of(lhs[0]);
if (pos != string::npos)
return lhs[0] < rhs[pos];
}
}
return true;
}
};
int main(int argc, char **argv)
{
vector<int> input2 = {0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0};
string target2 = string(input2.size(), '0');
Solution sln;
assert(sln.largestNumber(input2) == target2);
return 0;
}
这是leetcode 179的问题,代码正在运行并在ubuntu上使用g ++构建。当向量是较小的向量时,代码进展顺利。但是,当向量较大时,该过程将在排序行中存在段错误。结果很模糊,我想知道我的代码有什么问题。