https://leetcode.com/problems/largest-number/
When I was solving the above problem, I came across the case where std::sort()
was giving me a runtime error, but replacing it with std::stable_sort()
then there was no runtime error. Why?
Line is highlighted with the arrow sign on right
Code:
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;
}
};
TestCase:
[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]
Can anybody give me the reason why this happened?
comp
away entirely?main
? Where are your#include
s?