题目描述
- 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3, 32, 321},则打印出这3个数字能排成的最小数字321323。
算法分析
- 先排序, 排序规则如下:
- 若ab > ba 则 a > b;
- 若ab < ba 则 a < b;
- 若ab = ba 则 a = b。
提交代码:
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
if (numbers.empty())
return string();
QuickSort(numbers, 0, numbers.size() - 1);
string result;
for (int each : numbers)
result += to_string(each);
return result;
}
/* 快速排序 */
void QuickSort(vector<int> &numbers, int start, int end)
{
if (start < end)
{
int index = Partition(numbers, start, end);
QuickSort(numbers, start, index - 1);
QuickSort(numbers, index + 1, end);
}
}
int Partition(vector<int> &numbers, int start, int end)
{
int pivotalkey = numbers[0];
while (start < end)
{
while (start < end && newCompare(pivotalkey, numbers[end]))
--end;
swap(numbers[start], numbers[end]);
while (start < end && newCompare(numbers[start], pivotalkey))
++start;
swap(numbers[start], numbers[end]);
}
return start;
}
/* 比较方法 */
bool newCompare(int left, int right)
{
string leftString = to_string(left);
string rightString = to_string(right);
string s1 = leftString + rightString;
string s2 = rightString + leftString;
return s1 <= s2;
}
};
测试代码:
// ====================测试代码====================
void Test(const char* testName, vector<int> numbers, const char* expectedResult)
{
if (testName != nullptr)
printf("%s begins:\n", testName);
if (expectedResult != nullptr)
printf("Expected result is: \t%s\n", expectedResult);
Solution s;
printf("Actual result is: \t");
string result = s.PrintMinNumber(numbers);
cout << result << endl;
}
void Test1()
{
vector<int> numbers = { 3, 5, 1, 4, 2 };
Test("Test1", numbers, "12345");
}
void Test2()
{
vector<int> numbers = { 3, 32, 321 };
Test("Test2", numbers, "321323");
}
void Test3()
{
vector<int> numbers = { 3, 323, 32123 };
Test("Test3", numbers, "321233233");
}
void Test4()
{
vector<int> numbers = { 1, 11, 111 };
Test("Test4", numbers, "111111");
}
// 数组中只有一个数字
void Test5()
{
vector<int> numbers = { 321 };
Test("Test5", numbers, "321");
}
void Test6()
{
Test("Test6", vector<int>(), "");
}
int main(int argc, char* argv[])
{
Test1();
Test2();
Test3();
Test4();
Test5();
Test6();
return 0;
}