我已经为这个问题写了一个代码:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
基本上我试图在这段代码中实现的是首先对最高有效数字使用基数排序逻辑,并按降序排列它。后来我正在做第二个最重要的数字等等。我通过传递一个对 vector 来使用 std::sort()
函数,其中第一个是值,第二个是索引。以下是我的代码:
bool radixOrder(pair<int,int> p1, pair<int,int> p2)
{
int val1=p1.first;
int e1=p1.second;
int val2=p2.first;
int e2=p2.second;
if(val1==val2 && e1==e2)
{
return val1==val2;
}
else if(((val1/e1)%10) == ((val2/e2)%10))
{
while(val1/e1 == val2/e2)
{
if(e1/10!=0)
e1=e1/10;
if(e2/10!=0)
e2=e2/10;
}
return (val1/e1)%10 > (val2/e2)%10;
}
else
{
return (val1/e1)%10 > (val2/e2)%10;
}
}
vector<pair<int,int> > createVNew(vector<int>& v)
{
vector<pair<int,int> > temp;
for(int i=0; i<v.size(); i++)
{
cout << i << endl;
int val=v[i], e=1;
if(v[i]==0)
{
temp.push_back(make_pair(val, 1));
}
else
{
while((e/v[i])==0)
e*=10;
if(e!=v[i])
{
temp.push_back(make_pair(val,e/10));
}
else if(e==v[i])
{
temp.push_back(make_pair(val,e));
}
}
}
return temp;
}
string largestNumber(vector<int>& v)
{
int e=1;
vector< pair<int,int> > vnew=createVNew(v);
sort(vnew.begin(), vnew.end(), radixOrder);
stringstream s;
for(int i=0; i<vnew.size(); i++)
{
s<<vnew[i].first;
}
return s.str();
}
largestNumber(..)
是我的函数,它返回所需的字符串。现在这段代码适用于我可以尝试的大多数非零输入。但是当输入是一个由 0 组成的长 vector 时,类似于:
[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]
它给出了浮点异常。
我曾尝试寻找解决方案,但未能成功。我是 cpp 的初学者,任何帮助都会很棒。
最佳答案
您的 radixSort
函数违反了 Compare
requirements ,即非自反性(即 radixOrder(x, x)
必须返回 false
但它返回 true
因为执行转到第一个 if
分支)。
所以你在这里得到了一个未定义行为的经典例子。我认为应该以某种方式重写这段代码
if (e1==e2)
{
return val1 > val2;
}
不过,我可以通过将输入数字作为字符串倒序排序来解决问题。
关于c++ - 排序函数给出大量输入 0 的浮点异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30840491/