【发布时间】:2020-09-14 02:17:14
【问题描述】:
https://leetcode.com/problems/largest-number/
当我解决上述问题时,我遇到了std::sort() 给我一个运行时错误的情况,但是用std::stable_sort() 替换它然后没有运行时错误。为什么?
行以右侧箭头符号突出显示
代码:
class Solution {
public:
string reverse(string str)
{
int n=str.length();
for(int i=0;i<n/2;i++)
{
swap(str[i],str[n-i-1]);
}
return str;
}
static bool comp(string s1,string s2)
{
int min_val=min(s1.length(),s2.length());
int i=0;
bool flag=false;
for(;i<min_val;i++)
{
if((s1[i]-'0')==(s2[i]-'0'))
{
flag=true;
continue;
}
return (s1[i]-'0')>(s2[i]-'0');
}
if(flag==true && s1.length()==s2.length())
{
return s1==s2;
}
string s1_temp=s1;
string s2_temp=s2;
s1_temp+=s2;
s2_temp+=s1;
return s1_temp>s2_temp;
}
string largestNumber(vector<int>& nums)
{
string str="";
vector<string> inp;
for(int i=0;i<nums.size();i++)
{
string temp="";
long long int num=nums[i];
if(num!=0)
{
while(num!=0)
{
temp+=((num%10)+'0');
num/=10;
}
}
else
{
temp+=(num+'0');
}
inp.push_back(reverse(temp));
}
stable_sort(inp.begin(),inp.end(),comp); // <-- This Line
string res="";
for(int i=0;i<inp.size();i++)
{
res+=inp[i];
}
cout<<"yes"<<endl;
if(res[0]=='0')
{
return "0";
}
return res;
}
};
测试用例:
[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]
谁能告诉我发生这种情况的原因?
【问题讨论】:
-
常规排序有什么错误?
-
为什么需要自定义比较功能?你不能完全离开
comp吗? -
** 以下是运行时错误 **:第 431 行:字符 55:运行时错误:指针索引表达式以 0xbebebebebebebe 为基数溢出到 0x7d7d7d7d7d7d7d7c (basic_string.h)
-
您的代码不完整。
main在哪里?你的#includes 在哪里?
标签: c++ string sorting stl stable-sort