【发布时间】:2017-08-07 14:29:41
【问题描述】:
我正在尝试解决以下问题https://www.interviewbit.com/problems/largest-number/:给定一个非负整数列表,将它们排列成最大数。
例如:
给定 [3, 30, 34, 5, 9],最大的形成数是 9534330。
注意:结果可能会很大,所以需要返回字符串而不是整数。
我已经能够使用基于比较的排序技术解决并实现它。也就是说,给定两个数字 X 和 Y,我比较两个数字 XY(Y 附加在 X 的末尾)和 YX(X 附加在 Y 的末尾)。如果 XY 较大,则输出中 X 应该在 Y 之前,否则 Y 应该在之前。以下是代码:
string Solution::largestNumber(const vector<int> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
vector<string> myvec;
for (int i = 0; i < A.size(); i++)
{
string s = to_string(A[i]);
myvec.push_back(s);
}
sort(myvec.begin(),myvec.end(),mycomp());
string s = "";
auto it = myvec.begin();
while (it != myvec.end())
{
string p = *it;
s = s + p;
it++;
}
return s;
}
struct mycomp
{
inline bool operator() (const string &p1, const string &p2)
{
string s1 = p1.append(p2);
string s2 = p2.append(p1);
if (s1.compare(s2) < 0)
return false;
else
return true;
}
};
但是,问题是,我必须将两个函数合并为一个,因为我只需要实现单个函数。我无法再定义一个函数,因为我无法控制整段代码(查看链接的提交部分)。因此,我的问题是,如何通过在函数string Solution::largestNumber(const vector<int> &A) 中定义比较器来使用它。谢谢!
【问题讨论】:
-
我认为你可以在面试位有多种方法。不必用一种方法编写所有内容。
-
使用 lambda!而不是
sort(myvec.begin(),myvec.end(),mycomp());写sort(myvec.begin(),myvec.end(),[](const string &p1, const string &p2) -> bool { /* the operator()s content */ }); -
while (it != myvec.end()) { string p = *it; s = s + p; it++; }-- 可以改写为string p = std::accumulate(myvec.begin(), myvec.end(), std::string());。不需要临时字符串或临时迭代器。